美文网首页
为EventTrigger添加自定义事件

为EventTrigger添加自定义事件

作者: Walk_In_Jar | 来源:发表于2018-08-15 11:29 被阅读0次
               //tempObject 为需要添加事件的物体
                GameObject tempObject;//!!!
                EventTrigger trigger = tempObject.AddComponent<EventTrigger>();
                EventTrigger.Entry entry = new EventTrigger.Entry();
                entry.eventID = EventTriggerType.PointerDown;  //定义为哪种触发事件
                entry.callback.AddListener((data) => { OnDragDelegate((PointerEventData)data, tempObject); });
                trigger.triggers.Add(entry);
    
    
        public void OnDragDelegate(PointerEventData data, GameObject go)
        {
            dragGO = go;
        }
    

    为按钮添加自定义事件

    using UnityEngine;
    using UnityEngine.UI;
    
    public class Example : [MonoBehaviour]
    {
        //Make sure to attach these Buttons in the Inspector
        public Button m_YourFirstButton, m_YourSecondButton;
    
        void Start()
        {
            Button btn1 = m_YourFirstButton.GetComponent<Button>();
            Button btn2 = m_YourSecondButton.GetComponent<Button>();
    
            //Calls the TaskOnClick/TaskWithParameters method when you click the Button
            btn1.onClick.AddListener(TaskOnClick);
            btn2.onClick.AddListener(delegate {TaskWithParameters("Hello"); });
        }
    
        void TaskOnClick()
        {
            //Output this to console when the Button is clicked
            [Debug.Log](https://docs.unity3d.com/ScriptReference/Debug.Log.html)("You have clicked the button!");
        }
    
        void TaskWithParameters(string message)
        {
            //Output this to console when the Button is clicked
            [Debug.Log](https://docs.unity3d.com/ScriptReference/Debug.Log.html)(message);
        }
    }
    

    相关文章

      网友评论

          本文标题:为EventTrigger添加自定义事件

          本文链接:https://www.haomeiwen.com/subject/mqgibftx.html