【转】一个新的UIButtonMessage 给NGUI,使用委托,自动选择Receiver提供的方法

http://blog.csdn.net/chiuan/article/details/9290651?utm_source=tuicool&utm_medium=referral

来分享一个新的NGUI按钮方法回调的脚本,个人不是很喜欢原来那个UIButtonMessage,根据原来稍微修改了下。会比原先的智能和优化代码结构,效率也会好些。

认识:一个按钮事件发生理应有2个东西:1、发生事件,2、接收对象

 

1、发生事件:

如上图,我们看见这是一个标准的NGUI创建后的按钮对象,添加了TTButtonMessage后,会提示选择发生的条件、接受者是谁、处理方法KEY

图中我们看到选择了一个Onclick方法KEY,这个Key是从Receiver身上获取的。

 

2、接受者

 

[csharp] view plain copy
 
 print?
  1. using UnityEngine;  
  2. using System.Collections.Generic;  
  3.   
  4. /// <summary>  
  5. /// TT button message Receiver,Sample.  
  6. /// chiuanwei 2013.5.7  
  7. /// </summary>  
  8.   
  9. public class SampleButtonReceiver:TTButtonReceiver  
  10. {  
  11.     public override void Start()  
  12.     {  
  13.         base.Start();  
  14.         Debug.Log("Start.");  
  15.         Debug.Log("Button Msg Length = " + ButtonMsgs.Count);  
  16.     }  
  17.  
  18.     #region For Button Msg  
  19.   
  20.     //Must implement init function of Button Receiver.  
  21.     //and init all function here.  
  22.     public override void InitButtonFunction()  
  23.     {  
  24.         base.InitButtonFunction(  
  25.             Msg.create("Onclick",Onclick)  
  26.             );  
  27.     }  
  28.   
  29.     void Onclick(GameObject go)  
  30.     {  
  31.         Debug.Log("THE Button IS Clicked.");  
  32.     }  
  33.  
  34.     #endregion  
  35. }  


上面就是一个最简单的接收者写法了,绑定在接收物体身上即可。

 

我们新建一个脚本继承TTButtonReceiver,然后复写Start()、InitButtonFunction()方法

1、在Start中要调用一下基类中的Start()执行初始化

2、在InitButtonFunction中,要调用base.InitButtonFunction(……),然后传入你需要创建的按键方法通过KEY - FUNCTION

例如我创建多个方法会如下调用:

 

[csharp] view plain copy
 
 print?
  1. base.InitButtonFunction(  
  2.             Msg.create("Onclick",Onclick),  
  3.                         Msg.create("Onclick2",Onclick2),  
  4.                         Msg.create("Onclick3",Onclick3)  
  5. );  


3、延伸用法、贴士:
1、继承Receiver后有接口可以提供外部获取某个KEY的方法是否存在:public Msg GetMsgByKey(string key)
2、如果Reciever变化,选择过的KEY不会自动Remove,而会在面板提示你Recevier是否存在这个KEY的方法

 

 

最后漏了补上:
打包好的文件,要先把NGUI导入后再导这个包:http://game.ceeger.com/forum/read.php?tid=11789&fid=16

 

 

 

 

 

 

 

NGUI 3.5 ----- UIButton OnClick  

NUGI点击button获取input的值
NGUI 3.5 ----- UIButton OnClick - Leslie - Leslie
 
using UnityEngine;
using System.Collections;
 
public class Main : MonoBehaviour {
   UIInput messageInput;
   UIButton sendButton;
void Start () {
//找到Message
messageInput = Gameobject.Find("MessageInput").GetComponent<UIInput>();
//找到SendButton
sendButton = Gameobject.Find("SendButton").GetComponent<UIButton>();
//NGUI3.0之后使用EventDelegate.Add添加监听事件
EventDelegate.Add(sendButton.onClick, delegate(){
SendMessageToServer();
});
 
void SendMessageToServer(){
string text = NGUIText.stripSymbols(messageInput.value);
Debug.Log("Text----> " + text);
}
 
 
}

posted on 2016-12-31 22:12  mimime  阅读(462)  评论(0编辑  收藏  举报