Why does this code create an infinite loop? Does it represent one loop when it instantiates a GameObject and then sets its parent?
public GameObject ui;
GameObject child;
private void Start()
{
for (int i = 0; i < 10; i++)
{
child = Instantiate(ui);
child.transform.SetParent(ui.transform,false);
}
}
>Solution :
Instantiation makes a copy of an object with all of its hierarchy. You’re making copy of ui and assigning it as a child of the original ui object, so your hierarchy now looks like this:
ui (original)
-ui (copy)
In the next iteration of loop ui object is getting cloned again and becomes this:
ui
-ui
-ui (copy of ui with new child)
--ui
On the third iteration it will be doubled again. See where it is going?
And finally, I assume that your script that copies the ui is… on that ui object, thus is also copied each time, leading to the endless loop.