According to the documentation, you cannot instantiate buttons except via prefab instantiate.


You might wonder why we don’t have a API methods to create the various types of controls, including visuals and everything. The reason is that there are an infinite number of way e.g. a button could be setup. Does it use an image, text, or both? Maybe even multiple images? What is the text font, color, font size, and alignment? What sprite or sprites should the image use? By letting you make a prefab and instantiate that, you can set it up exactly the way you want. And if you later want to change the look and feel of your UI you can just change the prefab and then it will be reflected in your UI, including the dynamically created UI.

What I'm trying to do is dynamically create a table of buttons, each one going to a level in my game. The amount of button depends on how many levels the user has unlocked.

I can create a prefab for a button, that's fine, but how do I go about assigning an OnClick event to each of these buttons with an appropriate 'levelIndex' parameter?

I can not find any scripting method to do this, and I'd like to avoid hacky solutions like creating 50 buttons and only showing the first N children.


2 Answers 2


Atach a script like this in your button prefab

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {

    public string levelName;

    void OnMouseDown() {

after button instantiation, access to levelName property via script (you can also add a public method setLevelName..)

  • \$\begingroup\$ I don't believe this is what I'm looking for. Let's say my game has 30 levels, and the user is on level 10. In the main menu, I want to build a table containing 10 buttons. I can do this via prefab. Each button has a set event with a parameter, which is currently set to "LoadLevel(int levelIndex)". There is no API for these buttons to set properties for them. I'm asking what the accepted workaround is for this situation. \$\endgroup\$
    – Daniel
    Sep 23, 2015 at 10:56
  • \$\begingroup\$ You can get the ExampleClass reference in the prefab using GetComponent \$\endgroup\$
    – Ricky AH
    Sep 23, 2015 at 13:56
  • \$\begingroup\$ Ah I see what is meant now, I'll give that a shot. Thanks. \$\endgroup\$
    – Daniel
    Sep 23, 2015 at 22:08

After much pain I've found my answer.

It turns out there actually IS an API in the UnityEngine.UI namespace. I believe the documentation may have meant it doesn't have a way to create GUI elements with no reference to instantiate.

UnityEngine.UI.Button has everything I need, no need for a custom class mentioned in the previous answer which wouldn't have allowed me to change the text of the button anyway.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .