Search code examples
c#unity-game-enginelocalinstantiationgameobject

How to use a local object before it is declared?


I am making an if statement and I am trying to check if a game object exists, If it does exist I want to destroy it and then recreate it. If it does not exist I want to create it.

I get the error cannot use local variable before it is not declared. I have tried declaring it before but then it says cannot use enclosing local scope.

How can I use variable before it is declared or scoped?

Here is my code.

if (x > 25)
        {
            if (newGameObject.scene.IsValid())
            {
                Destroy(newGameObject);
                GameObject newGameObject = GameObject.Instantiate(object1);
            }
            else
            {
                GameObject newGameObject = GameObject.Instantiate(object1);
            }
        }

Solution

  • You can't create a new variable called "newGameObject" if one already exists.

    So what TerribleDog is suggesting is you declare the property at the class level.

    class YourClass: MonoBehaviour 
    {
        GameObject newGameObject
        void SomeMethod 
        {
            Destroy(newGameObject);
            //Then here just set the class level property
            newGameObject = GameObject.Instantiate(object1);
        }
    }