1.针对特定单个按钮
此代码直接绑定到button上面无需其他操作
using UnityEngine;
using UnityEngine.UI;public class PrintHelloOnButtonClick : MonoBehaviour
{private Button button;void Start(){// 获取当前GameObject上的Button组件button = GetComponent<Button>();// 添加点击事件监听器if (button != null){button.onClick.AddListener(ButtonClicked);}}// 当Button被点击时触发的方法void ButtonClicked(){Debug.Log("你好");}
}
2.使用UnityEvent系统
此代码需要将目标按钮拖拽过来
using UnityEngine;
using UnityEngine.UI;public class PrintHelloOnButtonClick : MonoBehaviour
{public Button button;void Start(){// 添加点击事件监听器if (button != null){button.onClick.AddListener(ButtonClicked);}}// 当Button被点击时触发的方法void ButtonClicked(){Debug.Log("你好");}
}
3.Unity编辑器界面直接关联脚本方法
此代码需要自己添加鼠标单击事件
using UnityEngine;
using UnityEngine.UI;public class PrintHelloOnButtonClick : MonoBehaviour
{// 当Button被点击时触发的方法public void ButtonClicked(){Debug.Log("你好");}
}