给按钮通过选择挂载赋值的方式设置按钮功能是最常用的,但在开发的过程中发现,此种方式不适用于大型项目,在大型项目中,常常会出现挂载的组件赋值丢失引起的错误,因此更推荐这种通过代码进行赋值的方式。
示例图片:
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonTest : MonoBehaviour
{
private Button btn;
private void Awake()
{
btn = GameObject.Find("t1Button").GetComponent<Button>();
btn.onClick.AddListener(delegate { click01(); });
btn.onClick.RemoveAllListeners();
btn.onClick.AddListener(delegate { click02(); });
}
// Start is called before the first frame update
void Start()
{
}
public void click01()
{
Debug.Log("你好");
}
public void click02()
{
Debug.Log("耶");
}
}