欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

学习 Unity3d:将事件绑定到按钮

最编程 2024-05-03 21:20:06
...

 创建测试脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class myTest : MonoBehaviour
{
    // Start is called before the first frame update
    public Button _codeBindBtn = null;
    void Start()
    {
        if (_codeBindBtn != null)
        {
            _codeBindBtn.onClick.AddListener(onCodeBindBtnClick);
        }
    }

    // Update is called once per frame
    void 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下拉框选择脚本中对应的函数

 分别点击按钮,通过打印信息可以看到,按钮的点击事件绑定成功!

 

推荐阅读