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

时间:2014-03-03 07:06:19

标签: c# button dynamic unity3d ngui

我是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> ();
    }
}

1 个答案:

答案 0 :(得分:2)

使用预制件:

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