创建测试脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class myTest : MonoBehaviour
{// Start is called before the first frame updatepublic Button _codeBindBtn = null;void Start(){if (_codeBindBtn != null){_codeBindBtn.onClick.AddListener(onCodeBindBtnClick);}}// Update is called once per framevoid Update(){}public void onCodeBindBtnClick(){Debug.Log("code bind click");}public void onEditorBindBtnClick(){Debug.Log("editor bind click");}
}
将脚本挂载到载体,并绑定按钮
通过下面的代码绑定按钮点击事件
_codeBindBtn.onClick.AddListener(onCodeBindBtnClick);
也可以通过编辑器的设置绑定按钮的点击事件
选中待绑定的按钮->点击Button组件中On Click下方的+号->把绑定脚本的载体赋值给新增属性->点击No Function下拉框选择脚本中对应的函数
分别点击按钮,通过打印信息可以看到,按钮的点击事件绑定成功!