for(int i = 0; i < 5; i++)
{
//Cast it as a Button, not a game object
GameObject MyPanel = GameObject.Find ("MyPanelContent);
Button newButton = (Button)Instantiate(buttonPrefab);
newButton.transform.SetParent(MyPanel.transform,false);
Debug.Log (i);
}
Do you have to create it dynamically, as opposed to setting it in the scene itself?
if you do, Iâd suggest that you make a public GameObject prefab variable
as well as a public variable for âMyPanelâ which you connect (drag & drop) in the inspector.
I do not think you need to convert it to a button, based on the code shown here.
Later, if you ever need it in code, you can get the button component âŚ
Also worth noting that those lines can be condensed to one. There is an overload of Instantiate that takes the parent transform as an argument. Unity - Scripting API: Object.Instantiate
Whatâs the error, though? Is MyPanelContent null in your script? Does it even exist in the script?
Simply giving it the same name as how you named it in your hierarchy wonât make it exist (much less work) in your script.
You need to get a reference to it in the script. In a nutshell:
Add âpublic Transform Contentâ to your class.
A new âContentâ field will appear in the Inspector. Drag your âMyPanelContentâ panel onto this.
Use âContent.transformâ where needed in your script.
Note: I deliberately chose the name âContentâ to make it clear we are talking about two things here: The script reference, and what you see in the inspector.
ok, but Iâm a beginner,. How could I make it using that Script ?
for(int i = 0; i < 7; i++)
{
//Cast it as a Button, not a game object
GameObject newButton = Instantiate(prefab);
newButton.transform.SetParent(this.transform, false);
}
public Sprite mySprite; // outside of a method, assign in the inspector.
// then, inside the method where that code you posted is (after you make the button)
newButton.GetComponent<Image>().sprite = mySprite;
Thatâs itâŚDepends what you want. I mean, if youâre just changing the sprite once when it starts, you could make an array of 7 sprites and add spriteArray in that loop. Whatever makes sense for you.
Thank you, this really helped me. Without this, the object wasnât found to set it as parent. This. actually took me a night of headache of finding it, refactoring code everywhere. The up side is: at least my code is much cleaner now.
Sometimes these small mistakes can take the most of your time in programming.