Skip to main content

Unity中EventTrigger使用

Unity中EventTrigger使用

在Unity中,点击场景中的模型我们往往需要检测是否点击在了UI上,这时我们需要进行一系列的判断,往往效果还不好,因此我在场景中模型的点击也使用了EventTrigger,EventTrigger我们在UI上的使用比较常见,但是它也可以用于场景点击,并且能屏蔽点击到UI又响应了模型的点击事件,以下是点击事件的组件脚本

using UnityEngine;
using UnityEngine.EventSystems;
public class EventTriggerListener : EventTrigger
{
public delegate void VoidDelegate();
public delegate void EventDelegate(BaseEventData baseEventData);
public delegate void BoolDelegate(bool state);
public delegate void FloatDelegate(float delta);
public delegate void VectorDelegate(Vector2 delta);
public delegate void ObjectDelegate(GameObject obj);
public delegate void KeyCodeDelegate(KeyCode key);

public VoidDelegate onClick;
public EventDelegate onEventClick;
public VoidDelegate onDown;
public VoidDelegate onEnter;
public VoidDelegate onExit;
public VoidDelegate onUp;
public VoidDelegate onSelect;
public VoidDelegate onUpdateSelect;


static public EventTriggerListener Add(Transform transform)
{
EventTriggerListener listener = transform.GetComponent<EventTriggerListener>();
if (listener == null)
listener = transform.gameObject.AddComponent<EventTriggerListener>();
return listener;
}

public override void OnPointerClick(PointerEventData eventData)
{
if (onClick != null)
{
onClick();
}
if (onEventClick != null)
{
onEventClick(eventData);
}
}

public override void OnPointerDown(PointerEventData eventData)
{
if (onDown != null)
onDown();
}

public override void OnPointerEnter(PointerEventData eventData)
{
if (onEnter != null)
onEnter();
}

public override void OnPointerExit(PointerEventData eventData)
{
if (onExit != null)
onExit();
}

public override void OnPointerUp(PointerEventData eventData)
{
if (onUp != null)
onUp();
}

public override void OnSelect(BaseEventData eventData)
{
if (onSelect != null)
onSelect();
}

public override void OnUpdateSelected(BaseEventData eventData)
{
if (onUpdateSelect != null)
onUpdateSelect();
}
}

使用方法,只需要在模型对象上挂在脚本,该脚本注册下上面的脚本事件。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class EnvironmentClick : MonoBehaviour
{
private void Awake()
{
EventTriggerListener.Add(transform).onEventClick += OnGroundClick;
}
public void OnGroundClick(BaseEventData data)
{
if (Input.GetMouseButton(1)) return;
if (Input.GetMouseButton(2)) return;

//do something

}

}