【Unity】 基础交互入门(按钮点击事件的三种方法) | 您所在的位置:网站首页 › 点击按钮触发事件的代码 › 【Unity】 基础交互入门(按钮点击事件的三种方法) |
基础交互入门(按钮点击事件的三种方法)
一、在按钮绑定事件二、直接通过脚本绑定事件三、脚本创建按钮绑定方法四、拓展阅读
一、在按钮绑定事件
1、在资源面板创建C#脚本 2、创建点击事件需要执行的代码(这里以loadMain为例),新增一个叫OnStartButtonClick的Public方法。 using System.Collections; using System.Collections.Generic; using UnityEngine; public class loadMain : MonoBehaviour { void Start() { } void Update() { } public void OnStartButtonClick() { Debug.Log("prefabName1");//只能运行时看到输出,可以换其他点击事件。 } }可以选择生成或者调试,从VS更新代码到Unity。 3、场景中创建Button和empty(生成空的GameObject) 4、将代码挂在刚刚的GameObject上(这里将GameObject重命名为loader),直接从资源窗口拖动到面板即可。 5、点击Button,找到面板的onclick(),选择刚刚的GameObject(即loader) 6、在右侧选择对应的方法。 二、直接通过脚本绑定事件 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;//Button组件的依赖 public class a : MonoBehaviour { private Button btn_Start;//定义一个Button类型的变量 // Start is called before the first frame update void Start() { btn_Start = GameObject.Find("Button").GetComponent();//通过Find查找名称获得我们要的Button组件 btn_Start.onClick.AddListener(OnStartButtonClick);//监听点击事件 } private void OnStartButtonClick() { Debug.Log("点击事件"); } // Update is called once per frame void Update() { } } 三、脚本创建按钮绑定方法 void createBtn() { GameObject itemList = GameObject.Find("itemList"); for (int i = 0; i |
CopyRight 2018-2019 实验室设备网 版权所有 |