Monday, August 29, 2016

c# - What are the steps to instantiate a button in Unity?


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



Answer



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

}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...