简体   繁体   中英

How to dynamically create button using NGUI (Unity)

I'm new in both unity and NGUI, I couldn't figure how to assign custom atlas and sprite into the button dynamically.

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

Use prefabs:

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

So, create a game object in the scene and add your createButton script. Then create a button using the NGUI widget wizard and save that as a prefab. Then, link that prefab to your createButton.myNguiButtonPrefab field in the inspector. Finally, add a custom script to the button prefab that would handle what happens when the button is clicked based on whatever parameters you care about, like so:

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
    }
}

And if you want to be really fancy, you can change your createButton to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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