纳金网

标题: 4.6后新版GUI - uGUI中控件事件的写法 [打印本页]

作者: 王者再临    时间: 2014-8-31 10:53
标题: 4.6后新版GUI - uGUI中控件事件的写法
除了在属性面板中手动给Button等添加事件外,终于搞定了用代码添加事件的方法。主要是手动添加太不方便了,而且代码方扩展、维护。创建Canvas、Button什么的在面板里。。。主要贴代码
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.Events;//引用事件命名空间
  4. using UnityEngine.UI;//引用UI命名空间

  5. public class Test : MonoBehaviour
  6. {
  7.         // Use this for initialization
  8.         void Start ()
  9.     {
  10.         //定义Action,并赋予delegate方法
  11.         UnityAction<Button> btnActions = new UnityAction<Button>(onClick);
  12.         //找到Button控件,并订阅事件
  13.         Button btn = gameObject.GetComponent<Button>();
  14.         btn.onClick.AddListener(btnActions);
  15.         }

  16.     void onClick(Object obj)
  17.     {
  18.         Debug.Log("button===========");
  19.         Debug.Log("button-----------" + obj.name);
  20.     }
  21. }

复制代码

作者: hyui    时间: 2014-9-1 04:37
感谢分享!!@~
作者: kaifly8888    时间: 2014-9-19 22:04
谢谢不错的文章




欢迎光临 纳金网 (http://www.narkii.com/club/) Powered by Discuz! X2.5