Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this code create an infinite loop?when Instantiate a gameobject and set it parent

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading