2
\$\begingroup\$

Given a Canvas test_canvas containing a Button test_button and an empty GameObject that manages instantiation and scripts and the like called test_manager, what are the steps to instantiate this button through code as opposed to having it already there?

I've tried making the button a prefab and instantiating it as I would any other object but that didn't work. I tried making the canvas a prefab and then trying the button but nothing. I've searched around for quite some time and there's mention of RectTransform and SetParent but steps or specific details would clear up my confusion

\$\endgroup\$
4
\$\begingroup\$

Prefab your Canvas and a Button and add this script to the test_manager gameobject

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

public class TestManagerScript : MonoBehaviour {
public GameObject canvas;
public GameObject button;

    void Start () {
        GameObject newButton = Instantiate(button) as GameObject;
        newButton.transform.SetParent(newCanvas.transform, false);
    }
}

be sure to drag the prefab button and prefab canvas to the public field slots this creates on the test_manager gameobject.

If you are also Instantiating the canvas you want to keep in mind that the UI will display from top to bottom as it is listed in the hierarchy. So you would want something like this.

 void Start () {

        GameObject newCanvas = Instantiate(canvas) as GameObject;
        GameObject newButton = Instantiate(button) as GameObject;
        newButton.transform.SetParent(newCanvas.transform, false);
    }
\$\endgroup\$
1
\$\begingroup\$

You may want to do something like this if you don't want to use prefabs.

public void CreateButton(Transform panel ,Vector3 position, Vector2 size,  
UnityEngine.Events.UnityAction method)
{
    GameObject button = new GameObject();
    button.transform.parent = panel;
    button.AddComponent<RectTransform>();
    button.AddComponent<Button>();
    button.transform.position = position;
    button.GetComponent<RectTransform>().SetSize(size);
    button.GetComponent<Button>().onClick.AddListener(method);
}
\$\endgroup\$
0
\$\begingroup\$

Create a Ui Button at runtime, Working example without prefabs.

    public static UnityEngine.UI.Button UiTexturedButton(Sprite sprite, Vector2 size, GameObject canvas)
    {
        GameObject go = new GameObject("Textured button (" + sprite.name + ")");

        Image image = go.AddComponent<Image>();
        image.sprite = sprite;

        UnityEngine.UI.Button button = go.AddComponent<UnityEngine.UI.Button>();
        go.transform.SetParent(canvas.transform, false);

        image.rectTransform.sizeDelta = size;

        return button;
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.