- Home /
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 ?
I would recommend removing your dependence on the Find function altogether. Ins$$anonymous$$d, keep track of objects yourself in a manager class of some sort.
BTW your theory about what's going on here could be tested by putting the code into a coroutine and yielding after the deletion.
Answer by kaarloew · Dec 05, 2018 at 11:00 AM
Delete happens in same frame, so you have to delay the create/instantiate. Or better yet, use object pooling.
There is also DestroyImmediate https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html