-1

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);
            }
        }
TeachMeEverything
  • 138
  • 1
  • 1
  • 13

2 Answers2

3

Declare it globally first.

GameObject obj;

Then on a method you can initialize it.

public void try()
{
    obj = new GameObject();
} 
TerribleDog
  • 1,237
  • 1
  • 8
  • 31
2

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);
    }
}
Allen Rufolo
  • 1,173
  • 1
  • 11
  • 14
  • Change it to `GameObject newGameObject = null;` https://www.google.com/search?q=use+of+unssigned+variable – mjwills Mar 27 '19 at 03:53
  • 1
    Change `newGameObject.scene.IsValid()` to `newGameObject != null && newGameObject.scene.IsValid()` as well. – mjwills Mar 27 '19 at 03:58
  • I have tried newGameObject != null && newGameObject.scene.IsValid() That worked , but it does not destroy the objects, they remain on the screen. – TeachMeEverything Mar 27 '19 at 04:03