GameObject.find("name") doesn't work if executed in the same loop of...

Hello,

I have a big problem : When I run the following code manually, it works.

  if (Input.GetKeyDown(KeyCode.Space))
            {
                // do something and delete some gameobjects
            }
  if (Input.GetKeyDown(KeyCode.M))
            {       
                for (int i = 1; i <= popini + 1; i++) 
                {
                    if (!GameObject.Find("SpherePreset_" + i))
                    {
                        // do something and create some gameobjects this name
                    }

But if I run it in a loop (in one time), it doesn’t work …

  if (Input.GetKeyDown(KeyCode.Space))
            {
                // do something and delete some gameobjects
                
                for (int i = 1; i <= popini + 1; i++) 
                {
                    if (!GameObject.Find("SpherePreset_" + i))
                    {
                        // do something and create some gameobjects with this name
                    }

In this code, unity doesn’t enter in the loop where I create my name for my new gameobjets…
I think, for Unity, the Gameobjects still exist because the delete of gameobjects is done in the same loop of the create gameobjects.

Is there a solution please ?

Delete happens in same frame, so you have to delay the create/instantiate. Or better yet, use object pooling.

There is also DestroyImmediate