- 最后登录
- 2021-7-6
- 注册时间
- 2012-12-27
- 阅读权限
- 90
- 积分
- 76145
 
- 纳金币
- 53488
- 精华
- 316
|
Selectable<----Button (Button继承自Selectable)
OnClick 按钮点击事件.
添加与删除事件的操作:
1. 在Inspector面板中直接拖拽物体给Button属性下的OnClick事件中选择事件函数.
2. 通过代码操作.
脚本UIEventTest.cs- using UnityEngine;
- using System.Collections;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- public class UIEventTest : MonoBehaviour
- {
- public Button button;
- public Text text;
- void Start ()
- {
- button.onClick.AddListener (OnClicke);
- button.onClick.AddListener (
- delegate {text.color = Color.green; } //匿名委托
- );
- }
- public void OnClick ()
- {
- text.text = "Clicked:" + name;
- Debug.Log (text.text);
- }
- }
复制代码 将脚本UIEventTest.cs拖拽到按钮上.拖拽目标Text放到脚本变量里.
可以在脚本中删除所有事件.button.onClick.RemoveAllListeners();
也可以删除指定事件 button.onClick.RemoveListener(OnClick);
事件被移除掉之后匿名委托事件还存在.- using UnityEngine;
- using System.Collections;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- public class UIEventTest : MonoBehaviour
- {
- private Button button;
- public Text text;
- void Start ()
- {
- button = gameObject.GetComponent<Button> ();
- button.onClick.AddListener (OnClick);
- button.onClick.AddListener (delegate {
- text.color = Color.green;
- button.onClick.RemoveListener (OnClick);
- Debug.Log ("delegate event.");
- });
- }
- public void OnClick ()
- {
- text.text = "Clicked:" + name;
- Debug.Log (text.text);
- }
- }
复制代码 删除点击事件后, 匿名委托的事件在.
unity不支持给事件传递多个参数,但是我们可以通过传递一个GameObject类型的参数.
间接的可以访问此GameObject的所有属性.
可以把某个类放到GameObject上.然后把这个GameObject传进来.
比如:整一个 test.cs脚本如下
- using UnityEngine;
- using System.Collections;
- public class test : MonoBehaviour
- {
- public string name;
- public int age;
- public float hight;
- public bool isDead;
- void Start ()
- {
- name = "kitty";
- age = 1;
- hight = 2;
- isDead = false;
- }
- }
复制代码 把这个脚本放到一个GameObject上面.
然后把这个GameObjcet物体拖拽到 放有UIEventTest2.cs脚本的按钮身上.
UIEventTest2.cs- using UnityEngine;
- using System.Collections;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- public class UIEventTest2 : MonoBehaviour
- {
- public void OnClick (GameObject obj)
- {
- test t = obj.GetComponent<test> ();
- Debug.Log ("[pet attribute]");
- Debug.Log ("name:" + t.name);
- Debug.Log ("age:" + t.age);
- Debug.Log ("hight:" + t.hight);
- Debug.Log ("isAlive:" + !t.isDead);
- }
- }
复制代码 在按钮的属性中OnClick中选择我们自己定义的按钮点击处理事件.把这个拥有test脚本的GameObject物体给这个事件函数做参数.
然后就可以用了.
|
|