繁体   English   中英

如何使用NGUI动态创建按钮(Unity)

[英]How to dynamically create button using NGUI (Unity)

我是Unity和NGUI的新手,我无法想象如何动态地将自定义图集和精灵分配到按钮中。

using UnityEngine;
using System.Collections;

public class createButton : MonoBehaviour {
    public createButton(){
        GameObject newButton = new GameObject ();
        newButton.name = "newButton" + 1;

        //go.AddComponent<UISprite> ();
        newButton.AddComponent<UIButton> ();
        newButton.AddComponent<UISprite> ();
    }
}

使用预制件:

public class createButton : MonoBehaviour {
    public GameObject myNguiButtonPrefab;
    private int nextId;

    public createButton(){
        GameObject newButton = (GameObject)Instantiate(myNguiButtonPrefab);
        newButton.name = "newButton" + (nextId++);

        MyButtonScript buttonScript = newButton.GetComponent<MyButtonScript>();
        buttonScript.Setup(/* some parameters */);
    }
}

因此,在场景中创建一个游戏对象并添加您的createButton脚本。 然后使用NGUI小部件向导创建一个按钮,并将其另存为预制件。 然后,将预制件链接到检查器中的createButton.myNguiButtonPrefab字段。 最后,在按钮预制件中添加一个自定义脚本,用于处理根据您关注的任何参数单击按钮时发生的情况,如下所示:

public class MyButtonScript : MonoBehaviour {
    public void Setup(/* Some parameters */){
        // Do some setting up
        UISprite sprite = GetComponent<UISprite>();
        sprite.spriteName = "someSpriteBasedOnTheParametersPassed";
    }

    void OnClick(){
        // Do something when this button is clicked based on how we set this button up
    }
}

如果你想要真正的幻想,你可以将你的createButton更改为:

public class createButton : MonoBehaviour {
    public MyButtonScript myNguiButtonPrefab;
    private int nextId;

    public createButton(){
        MyButtonScript newButton = (MyButtonScript )Instantiate(myNguiButtonPrefab);
        newButton.name = "newButton" + (nextId++);
        newButton.Setup(/* some parameters */);
    }
}

暂无
暂无

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

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