新的UI系统消息传递被全新设计,该系统用MonoBehaviour 来实现自定义的接口,以便可以接受来自消息系统的回调。当一个对象被消息的执行指定,那么这个对象的所有实现了自定义接口的脚本将被通知,指定的方法将被执行。
1.定义一个接口ICustomMessageTarget继承IEventSystemHandler, 这样当发送此类型消息时,实现此接口的脚本所在的对象将会被通知。
using UnityEngine; using UnityEngine.EventSystems; using System.Collections; public interface ICustomMessageTarget : IEventSystemHandler { void Message1(); void Message2(); }
2.测试脚本CustomMessageTarget实现ICustomMessageTarget,加到一个对象上。
using UnityEngine; using System.Collections; public class CustomMessageTarget : MonoBehaviour , ICustomMessageTarget { public void Message1() { Debug.Log("Message1 received."); } public void Message2() { Debug.Log("Message2 received."); } }
这样当执行下面代码时事件将被触发
ExecuteEvents.Execute<ICustomMessageTarget>(go, null, (x, y) => x.Message1());
同时EventSystem还提供了大量的事件, 只需要在脚本中实现这些接口就可以触发相应的方法
- IPointerEnterHandler - OnPointerEnter - Called when a pointer enters the object
- IPointerExitHandler - OnPointerExit - Called when a pointer exits the object
- IPointerDownHandler - OnPointerDown - Called when a pointer is pressed on the object
- IPointerUpHandler - OnPointerUp - Called when a pointer is released (called on the original the pressed object)
- IPointerClickHandler - OnPointerClick - Called when a pointer is pressed and released on the same object
- IInitializePotentialDragHandler - OnInitializePotentialDrag - Called when a drag target is found, can be used to initialise values
- IBeginDragHandler - OnBeginDrag - Called on the drag object when dragging is about to begin
- IDragHandler - OnDrag - Called on the drag object when a drag is happening
- IEndDragHandler - OnEndDrag - Called on the drag object when a drag finishes
- IDropHandler - OnDrop - Called on the object where a drag finishes
- IScrollHandler - OnScroll - Called when a mouse wheel scrolls
- IUpdateSelectedHandler - OnUpdateSelected - Called on the selected object each tick
- ISelectHandler - OnSelect - Called when the object becomes the selected object
- IDeselectHandler - OnDeselect - Called on the selected object becomes deselected
- IMoveHandler - OnMove - Called when a move event occurs (left, right, up, down, ect)
- ISubmitHandler - OnSubmit - Called when the submit button is pressed
- ICancelHandler - OnCancel - Called when the cancel button is pressed
例子:
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class TestPointerEnterEvent : MonoBehaviour , IPointerEnterHandler , IPointerClickHandler { public void OnPointerEnter(PointerEventData data) { Debug.Log("Pointer enter."); } public void OnPointerClick(PointerEventData data) { Debug.Log("Pointer click."); } }
时间: 2024-12-06 03:44:39