如何使用 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 */);
    }
}

最新更新