Search code examples
c#buttondynamicunity-game-enginengui

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

Solution

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