1
\$\begingroup\$

I have a canvas object. I right click it and add a Button, which defaults to having a rect transform, image script, button script and text child object. I make it a prefab and delete it from my canvas. I want to have a data driven engine so I have an external list which I want to make into buttons. When I have my list loaded I attempt to create dynamic buttons by:

GameObject prefabButton = new GameObject("StandardButton");

This in the hierarchy but it doesn't have the image or button or text components added, only a transform.

Why doesn't it have the things the prefab has??

I read I might need to instantiate it, so I tried:

GameObject stdButton = (GameObject)Instantiate(prefabButton);

Again this creates another object in my hierarchy with nothing but a basic transform.

What is the difference between this object and the one I created before? Why instantiate at all?

\$\endgroup\$
2
  • 2
    \$\begingroup\$ In your second example, are you assigning prefabButton in the inspector? \$\endgroup\$
    – Static
    Commented Apr 8, 2015 at 7:16
  • \$\begingroup\$ No. Prefab is only in the my assets folder. This code is in a script. I read somewhere that these two lines of code need to exist together to load in a prefab correctly. \$\endgroup\$ Commented Apr 9, 2015 at 6:54

1 Answer 1

2
\$\begingroup\$

Presuming you've saved the prefab out to your Resources folder in your project, you will need to load and instantiate it and then attach it to the canvas. Your code should be something like this:

Canvas canvasComponent = GameObject.Find("Canvas").GetComponent<Canvas>();
GameObject myButtonPrefab = Resources.Load<GameObject>("whatEverTheButtonPrefabIsCalled");
GameObject actualButton = GameObject.Instantiate(myButtonPrefab) as GameObject;
myButtonPrefab.transform.SetParent(canvasComponent.gameObject.transform, false);

Hope that helps.

\$\endgroup\$
3
  • \$\begingroup\$ No this did not help. I assume by Resources folder, you mean Assets Folder? Your second line results in myButtonPrefab being null. Changing it to 'GameObject myButtonPrefab = new GameObject("StandardButtonPrefab");' (like I have already in my code) returns an object. My questions still remain. \$\endgroup\$ Commented Apr 9, 2015 at 6:45
  • \$\begingroup\$ My mistake, I did not know you must have a folder actually called "Resources" for 'Resources.Load' to work. Seeing how essential loading prefabs is, you'd think the default unity project would have that... \$\endgroup\$ Commented Apr 14, 2015 at 5:41
  • \$\begingroup\$ Worked for me, though I had to change the 4th line to this (as the prefab button can't be used to setparent): actualButton.transform.SetParent(canvasComponent.gameObject.transform, false); \$\endgroup\$ Commented Aug 13, 2015 at 17:03

You must log in to answer this question.

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