nix86
nix86

Reputation: 3037

In a Unity3D script an object created in the Update method is null everywhere else

I have created an object in the Update function and stored it in a global reference, but in the Loop it is always null.

//The variable foo is global so it should be accessible everywhere
Foo foo; 

void Start()
{
    //The Loop method is called every 0.5 seconds
    InvokeRepeating("Loop", 1f, 0.5f);
}

void Update()
{
    if(Input.GetButtonDown("Jump"))
        foo=new Foo();
}

void Loop()
{
    if(foo==null)
        Debug.Log("foo is null");//foo is always null
    else
        Debug.Log("foo is not null");//this line is never executed
}

When I press the "Jump" button, the is the "Space" button, foo is created but in the Loop it is always null. Why?

Upvotes: 0

Views: 58

Answers (2)

Max Yankov
Max Yankov

Reputation: 13277

You can not use contructors with MonoBehaviours. Please, use AddComponent method to add MonoBehaviour to an existing object instead.

Also, be aware that == operator is overridden for Unity objects, and a == null can be true while the a reference is actually is not null. This is done for Destroy and DestroyImmediate methods to work, and can result in a lot of confusion.

Upvotes: 1

nix86
nix86

Reputation: 3037

I think that I've found the answer here:

http://docs.unity3d.com/ScriptReference/Object-operator_eq.html

The answer is at the bottom of the page.

GameObject go = new GameObject(); 
Debug.Log (go == null); // false

Object obj = new Object();
Debug.Log (obj == null); // true

If you create a GameObject the object will be different from null. Meanwhile if you create a normal Object the object will always be null. So it has nothing to do with the Update function.

Upvotes: 0

Related Questions