uGUI使用代码动态添加Button.OnClick()事件

uGUI出来这么久了,也一直没好好用用,主要是公司项目不用U3D。昨晚用了下Button,还是比较爽的。

主要说下用代码添加button.OnClick()事件的方法(使用属性面板添加的方法就不说了)

一、创建2D UI Panel,添加你需要的Button。

我添加了3个Button:BtnStart,BtnShop,BtnLeaderboards。



二、添加脚本


[JavaScript] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<font face= "Verdana," >    using UnityEngine; 
     using System.Collections; 
     using System.Collections.Generic; 
     using UnityEngine.Events; 
     using UnityEngine.UI; 
       
       
     public class MainMenu : MonoBehaviour { 
       
         // Use this for initialization 
         void Start () { 
             List<string> btnsName = new List<string>(); 
             btnsName.Add( "BtnPlay" ); 
             btnsName.Add( "BtnShop" ); 
             btnsName.Add( "BtnLeaderboards" ); 
       
             foreach(string btnName in btnsName) 
            
                 GameObject btnObj = GameObject.Find(btnName); 
                 Button btn = btnObj.GetComponent<Button>(); 
                 btn.onClick.AddListener(delegate() { 
                     this .OnClick(btnObj);  
                 }); 
             }  
        
       
         public void OnClick(GameObject sender) 
        
             switch (sender.name) 
            
             case "BtnPlay"
                 Debug.Log( "BtnPlay" ); 
                 break
             case "BtnShop"
                 Debug.Log( "BtnShop" ); 
                 break
             case "BtnLeaderboards"
                 Debug.Log( "BtnLeaderboards" ); 
                 break
             default
                 Debug.Log( "none" ); 
                 break
            
        
           
         // Update is called once per frame 
         void Update () { 
           
        
     }  </font>


测试一下,可以了。




我室友的是一个技术大神
这里分享他的网站  http://www.feehi.com 有需求的大家可以进去看看 这是他的博客网 http://blog.feehi.com/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值