How to Create UI Button Dynamically

Hi all

I am new bie unity. In my project i have to create 5 UI Button Dynamically using array list.and it display which

button is pressed. Could any one help me…

Thanks in Advance

Hi, the basics are explained in manual, it gives good overview of the process:

http://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html

  1. Make a nice button and save it as prefab.
  2. Instantiate it or Pool it.
  3. Add onClick events.

Confusing?
A simple example for you.:slight_smile:

 GameObject buttonPrefab;

    void MyAwesomeCreator()
    {
        GameObject go = Instantiate(buttonPrefab);
        var button = GetComponent<UnityEngine.UI.Button>();
        button.onClick.AddListener(() => FooOnClick());
    }
    void FooOnClick()
    {
        Debug.Log("Ta-Da!");
    }
7 Likes

Thanks eses and zhuchun for you help. When i run the above code first time it works . After that i run in another project it says

Type Button' does not contain a definition for onClick’ and no extension method onClick' of type Button’ could be found (are you missing a using directive or an assembly reference?)

I dont know how to solve this… Could any one help… Why it creates error…

Hi i have tested with the below code…

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
   
    public GameObject prefabButton;
    public RectTransform ParentPanel;
   
    // Use this for initialization
    void Start () {
       
        for(int i = 0; i < 5; i++)
        {
            GameObject goButton = (GameObject)Instantiate(prefabButton);
            goButton.transform.SetParent(ParentPanel, false);
            goButton.transform.localScale = new Vector3(1, 1, 1);
           
            Button tempButton = goButton.GetComponent<Button>();
            int tempInt = i;
           
            tempButton.onClick.AddListener(() => ButtonClicked(tempInt));
        }
       
       
    }
   
    void ButtonClicked(int buttonNo)
    {
        Debug.Log ("Button clicked = " + buttonNo);
    }
   
}

First Time it runs good. After that when i copied to another project. It shows the error…

NullReferenceException: Object reference not set to an instance of an object

Could any one help me… How to Solve the Problem…

2 Likes

I have run many button cs coding files from forum . It shows the same error…could any one help me…

NullReferenceException: Object reference not set to an instance of an object

Hi @Alexander21 ,

Could you perhaps give more information? Which line of code is the Error showing up at?

Could you perhaps also take a screenshot and show the actual Error?

Regards,
Jason

Thanks Jason for your help. Actually While run time it creates error. It creates single button after it shows the error.

NullReferenceException: Object reference not set to an instance of an object

while i click that error. It Points to this line…

tempButton.onClick.AddListener(()=> ButtonClicked(tempInt));

could any one help me…

Hi @Alexander21 ,

I ran your code in my game, the first time I ran it, it was fine.

And I managed to replicate your Error by removing the Button component from your prefab.

I’ve attached 2 images to help you in your understanding.

To get the results in 7.png, go to your prefabButton and addComponent → Button.

Edit: I do not know if this is your exact problem, so please test and let me know the results.

Regards,
Jason

2567469--178951--7.PNG
2567469--178952--8.PNG

Thanks jason… I have added the button component but The same 8.png error is happend while running my script…I am trying soon i will update

Hey, sorry for the confusing. You should have an Button attach on it, a safer way is RequireComponent, it checks your GameObject and provides suggestion. This header ensure that you won’t get null when GetComponent.

[RequireComponent(typeof(UnityEngine.UI.Button))]
public class MyAwsomeScriptAttachOn: MonoBehaviour
{ 
var button = GetComponent<UnityEngine.UI.Button>(); //button can't be null
}
3 Likes

You have not attached the prefab and the panel to your script components in unity…i think this is the reason

Yup and the OP specifically asked about instantiating a button, not a prefab you’re made prior.