Unity按钮点击事件

编程入门 行业动态 更新时间:2024-10-14 20:19:12

Unity<a href=https://www.elefans.com/category/jswz/34/1771318.html style=按钮点击事件"/>

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按钮点击事件

本文发布于:2024-02-06 16:55:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1750410.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   事件   Unity

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!