Home > Back-end >  How do I instantiate a prefab through a script in Unity C# correctly?
How do I instantiate a prefab through a script in Unity C# correctly?

Time:07-03

I am instantiating a prefab thru a script in Unity. It's kind of working but not really. The prefab shows up in the hierarchy with the correct name but in the scene, it cannot be seen. I have looked through every question I saw, that was similar but unfortunately, I couldn't solve my problem. I tried changing the Vector in the script and the position of the prefab itself. I appreciate any help.

public class ButtonControler : MonoBehaviour

[SerializeField] private Button[] buttonsList;
public GameObject button;

public void Awake()
{
   InitializeButtons();
}

private void InitializeButtons()
{
for (int i = 0; i < CsvManagerDownloader.experiments.Count; i  )
{
    string buttontext = "Experiment"   i;
    
    GameObject newButton = Instantiate(button, new Vector3(0, 0, 0), Quaternion.identity);
    newButton.GetComponentInChildren<Text>().text = buttontext;
  
    
}

(This script can only be called after CSVManagerDownloader, since the number of buttons is gathered from that script.)

CodePudding user response:

It seems that you are trying to instantiate an object that is supposed to be used inside Canvas (unity UI system) in the world space.

Canvas component on the root object is needed to render all child UI elements like Button, Text, Image, etc.

So, if you want your instantiated object with the Button component to be visible, make sure, that you place it in the hierarchy with the Canvas component attached to any of its parents.

Also, make sure that the EventSystem component is present at the scene to make Buttons work.

  • Related