0

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> ();
    }
}
Steven
  • 166,672
  • 24
  • 332
  • 435
user3373752
  • 3
  • 1
  • 1
  • 2
  • Is there a reason you're doing this dynamically rather than instantiating a prefab? – Dan Puzey Mar 03 '14 at 15:57
  • Dan Puzey: I would like to dynamically create different buttons with a single prefab, will this cause a mess? Or it is way too hard for me to do that currently. – user3373752 Mar 04 '14 at 03:04

1 Answers1

2

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 */);
    }
}
pek
  • 17,847
  • 28
  • 86
  • 99