按钮点击事件"/>
Unity按钮点击事件
一.可视化创建及事件绑定
首先给要在Inspector面板点击最下面的Add Component搜索Button
添加Button组件
然后在编写一段脚本添加到任意的游戏对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Text : MonoBehaviour
{/// <summary>/// 开始按钮点击后调用此方法/// </summary>public void OnStartButtonClick(){Debug.Log("哈哈哈哈!看,你好像是个憨憨!!");}
}
重点是:一定要是公开的public类型的方法!!
然后在button组件中找到箭头所指的
把挂载脚本的对象拖到 箭头指向的位置
然后 在箭头指向的位置
选择 我们刚刚的OnStartButtonClick()方法
运行之后点击按钮就完成了
二 .直接通过脚本绑定
创建一个脚本添加到任意游戏对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//后面要使用一些UI(该处就是Button)组件,所以一定要添加该命名空间public class Text : MonoBehaviour
{private Button btn_Start;//定义一个Button类型的变量private void Start(){btn_Start = GameObject.Find("btn_Start").GetComponent<Button>();//通过Find查找名称获得我们要的Button组件btn_Start.onClick.AddListener(OnStartButtonClick);//监听点击事件}/// <summary>/// 点击的之后调用的方法/// </summary>private void OnStartButtonClick(){Debug.Log("我是大聪明");}}
运行结果
更多推荐
Unity按钮点击事件
发布评论