UGUI事件监听总结

来源:互联网 发布:ios6.1.3软件源 编辑:程序博客网 时间:2024/06/11 05:14
Unity3D的uGUI系统的将UI可能触发的事件分为12个类型,即EventTriggerType枚举的  12个值。如下图所示:

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

  先以PointerClick为例。这个是用于某点点击事件。其他事件都可以根据相同的办法调用。

    之所以使用PointerClick为例。是因为在最后笔者会提到一个特殊的实现方式。而相比于其他事件类型,有且仅有Click事件存在特殊实现。

    我们要实现事件主要有3种方式:

    方式一:继承基础接口实现

    步骤一:创建ClickObject脚本。继承MonoBehaviour和IPointerClickHandler。

    

    步骤二:实现public void OnPointerClick(PointerEventData eventData)方法:

    步骤三:创建一个名为Panel_IPointer的空对象。并且将ClickObject脚本附加到对象上。

    步骤四:启动,并点击Panel_IPointer对象。在Console输出如下:

 

    方式二:Unity3D编辑器操作设置实现

    

步骤一:创建一个C#脚本。在脚本中添加一个public方法。

步骤二:创建一个命名为Empty的UI对象,用于接收和响应点击事件。创建一个名为Panel的UI对象,用于触发点击事件。

 

步骤三:Panel对象添加EventTrigger组件," Add New" -> 选择" PointerClick"。将Empty对象拖拽到触发者位置。然后点击"No Function"选择我们写在Test脚本中的OnTestClick事件。

 

    步骤四:设置好这些之后。我们的事件触发就已经完成了。运行Unity3D。点击窗口中Panel对象。Console输出内容如下:

    方式三:程序动态设置实现

    我们在日常的开发中。可能需要动态的需要变更绑定的事件。那么我们如何才能使用C#代码控制绑定触发事件呢?

    下面我们就介绍代码控制。ScriptControl.cs脚本


using UnityEngine;using System.Collections;using UnityEngine.UI;public class BtnControl : MonoBehaviour {    // Use this for initialization    void Start ()    {        var button = transform.gameObject.GetComponent<Button>();        if (button != null)        {            button.onClick.RemoveAllListeners();            button.onClick.AddListener(TestClick);        }    }    public void TestClick()    {        Debug.Log("Test Click. This is Type 4");    }        // Update is called once per frame    void Update () {            }}


原创粉丝点击