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

2023-06-05,,

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、接受者

    using UnityEngine;
    using System.Collections.Generic;
    /// <summary>
    /// TT button message Receiver,Sample.
    /// chiuanwei 2013.5.7
    /// </summary>
    public class SampleButtonReceiver:TTButtonReceiver
    {
    public override void Start()
    {
    base.Start();
    Debug.Log("Start.");
    Debug.Log("Button Msg Length = " + ButtonMsgs.Count);
    }
    #region For Button Msg
    //Must implement init function of Button Receiver.
    //and init all function here.
    public override void InitButtonFunction()
    {
    base.InitButtonFunction(
    Msg.create("Onclick",Onclick)
    );
    }
    void Onclick(GameObject go)
    {
    Debug.Log("THE Button IS Clicked.");
    }
    #endregion
    }

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

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

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

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

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

    base.InitButtonFunction(
    Msg.create("Onclick",Onclick),
    Msg.create("Onclick2",Onclick2),
    Msg.create("Onclick3",Onclick3)
    );

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的值

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);
}
 
 
}

【转】一个新的UIButtonMessage 给NGUI,使用委托,自动选择Receiver提供的方法的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。