//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);
}
}
网友评论