0

i want to destroy a game object that i instantiated and i get a lot of errors when i try to do so like "the name clone does not exist in the current context" , "cannot convert object expression to type UnityEngine.Object". i tried a lot of things i found online but nothing helps. here is my code :

if(distance<renderDistance)
    {
        if(!temp)
        {
            GameObject clone = Instantiate(chunk,transform.position,transform.rotation)as GameObject;
            temp = true;
        }
    }
    else
    {
        Destroy(clone);
    }
Steven
  • 166,672
  • 24
  • 332
  • 435
user3789296
  • 23
  • 3
  • 6

1 Answers1

2

You were getting "the name clone does not exist in the current context" error because you declared this variable ('clone') inside "if(!temp)" brackets and it hasn't existed after closing bracket.

Try this code:

GameObject clone = null;
if (distance < renderDistance)
{
    if(!temp)
    {
        clone = (GameObject)Instantiate(chunk, transform.position, transform.rotation);
        //be sure 'chunk' is GameObject type
        temp = true;
    }
}
else
{
    if (clone != null)
        Destroy(clone);
}

Let me know if you have any questions or need more help.

mateuszlewko
  • 1,110
  • 8
  • 18