使用预制件:
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 */);
}
}