添加鼠标侦听器

有时,你希望在组件本身提供的特定事件(特别是鼠标事件)上添加侦听器。为此,你必须使用 EventTrigger 组件自行添加它们:

using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof( EventTrigger ))]
public class CustomListenersExample : MonoBehaviour
{
    void Start( )
    {
        EventTrigger eventTrigger = GetComponent<EventTrigger>( );
        EventTrigger.Entry entry = new EventTrigger.Entry( );
        entry.eventID = EventTriggerType.PointerDown;
        entry.callback.AddListener( ( data ) => { OnPointerDownDelegate( (PointerEventData)data ); } );
        eventTrigger.triggers.Add( entry );
    }

    public void OnPointerDownDelegate( PointerEventData data )
    {
        Debug.Log( "OnPointerDownDelegate called." );
    }
}

各种 eventID 都是可能的:

  • PointerEnter
  • PointerExit
  • PointerDown
  • PointerUp
  • PointerClick
  • 拖动
  • 下降
  • 滚动
  • UpdateSelected
  • 选择
  • 取消
  • 移动
  • InitializePotentialDrag
  • BeginDrag
  • EndDrag
  • 提交
  • 取消