简体   繁体   English

以编程方式统一处理ngui的按钮事件

[英]handle ngui's button event programmatically in unity

I'm transferring from Unity's UI to NGUI. 我正在从Unity的UI转移到NGUI。

Formerly, I could add listeners to button with following scripts: 以前,我可以使用以下脚本将侦听器添加到button:

button.GetComponentInChildren<Button>().onClick.AddListener(() =>
{
    //codes that could be triggered by click the button. 
});

But when changing to NGUI, I can't make it work by: 但是当更改为NGUI时,我不能通过以下方式使其起作用:

EventDelegate.Set(go.GetComponent<UIButton>().onClick, OnButtonClickActive);

private void OnButtonClickActive()
{
   Debug.Log("active button clicked");
}

Finally, I made this work by adding a custom event to OnClick with the following script (using UIEventListener ): 最后,通过使用以下脚本(使用UIEventListener )向OnClick添加自定义事件来完成这项工作:

UIEventListener.Get(go).onClick += OnButtonClickActive;

And the event handler is defined as follows: 事件处理程序的定义如下:

private void OnButtonClickActive(GameObject go)
    {
        int level;
        int.TryParse(go.GetComponentInChildren<UILabel>().text, out level);
        Debug.Log(level + "active button clicked");
        ApplicationModel.CurrentLevel = ApplicationModel.Levels[level - 1];
        SceneManager.LoadScene("PlayScene");
    }

Note that, it might be a little bit silly to pass the parameter (level info) with the UILable component in the gameobject. 请注意,将参数(关卡信息)与游戏对象中的UILable组件一起传递可能有点愚蠢。 If there is other more elegant way, please let me know. 如果还有其他更优雅的方法,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM