Button-----------------------------------------------------------------------------------------------------
Selectable<----Button (Button继承自Selectable)
OnClick 按钮点击事件.
添加与删除事件的操作:
1. 在Inspector面板中直接拖拽物体给Button属性下的OnClick事件中选择事件函数.
2. 通过代码操作.
脚本UIEventTest.cs
[code]csharpcode:
01usingUnityEngine;
02usingSystem.Collections;
03usingUnityEngine.UI;
04usingUnityEngine.EventSystems;
05
06publicclassUIEventTest : MonoBehaviour
07{
08publicButton button;
09publicText text;
10voidStart ()
11{
12button.onClick.AddListener (OnClicke);
13button.onClick.AddListener (
14delegate{text.color = Color.green; }//匿名委托
15);
16}
17publicvoidOnClick ()
18{
19text.text ="Clicked:"+ name;
20Debug.Log (text.text);
21}
22}
将脚本UIEventTest.cs拖拽到按钮上.拖拽目标Text放到脚本变量里.
可以在脚本中删除所有事件.button.onClick.RemoveAllListeners();
也可以删除指定事件 button.onClick.RemoveListener(OnClick);
事件被移除掉之后匿名委托事件还存在.
[code]csharpcode:
01usingUnityEngine;
02usingSystem.Collections;
03usingUnityEngine.UI;
04usingUnityEngine.EventSystems;
05
06publicclassUIEventTest : MonoBehaviour
07{
08privateButton button;
09publicText text;
10voidStart ()
11{
12button = gameObject.GetComponent ();
13button.onClick.AddListener (OnClick);
14button.onClick.AddListener (delegate{
15text.color = Color.green;
16button.onClick.RemoveListener (OnClick);
17Debug.Log ("delegate event.");
18
19});
20}
21publicvoidOnClick ()
22{
23text.text ="Clicked:"+ name;
24Debug.Log (text.text);
25}
26}
删除点击事件后, 匿名委托的事件在.
unity不支持给事件传递多个参数,但是我们可以通过传递一个GameObject类型的参数.
间接的可以访问此GameObject的所有属性.
可以把某个类放到GameObject上.然后把这个GameObject传进来.
比如:整一个 test.cs脚本如下
[code]csharpcode:
01usingUnityEngine;
02usingSystem.Collections;
03
04publicclasstest : MonoBehaviour
05{
06publicstringname;
07publicintage;
08publicfloathight;
09publicboolisDead;
10voidStart ()
11{
12name ="kitty";
13age = 1;
14hight = 2;
15isDead =false;
16}
17}
把这个脚本放到一个GameObject上面.
然后把这个GameObjcet物体拖拽到 放有UIEventTest2.cs脚本的按钮身上.
UIEventTest2.cs
[code]csharpcode:
01usingUnityEngine;
02usingSystem.Collections;
03usingUnityEngine.UI;
04usingUnityEngine.EventSystems;
05
06publicclassUIEventTest2 : MonoBehaviour
07{
08publicvoidOnClick (GameObject obj)
09{
10test t = obj.GetComponent ();
11Debug.Log ("[pet attribute]");
12Debug.Log ("name:"+ t.name);
13Debug.Log ("age:"+ t.age);
14Debug.Log ("hight:"+ t.hight);
15Debug.Log ("isAlive:"+ !t.isDead);
16}
17}
在按钮的属性中OnClick中选择我们自己定义的按钮点击处理事件.把这个拥有test脚本的GameObject物体给这个事件函数做参数.
然后就可以用了.
网友评论