- Home /
this == null
How can it happen that this keyword returns null?
Even ReSharper tells that this condition is always false and yet, it return true in play mode and after exiting play mode.
this is not null only after assembly reload. This problem only occurs in Unity 5. In Unity 4.6 it does not occur.
[EDIT] Solution in comments.
Answer by CHPedersen · Mar 18, 2015 at 05:24 PM
It can happen in Unity because the equality operator is overloaded for scripts. Comparing to null does not check to see if the reference points to null, which would otherwise be the case in standard C#. Instead, it checks to see if the object is instantiated in the scene (technically, whether it exists in Unity's native C++ code backend).
ReSharper has no idea Unity is built this way. It assumes the equality operator works the same as for standard C#.
Thanks, I didn't know about the overloaded operator. But still, how is is possible that refering to enabled property on $$anonymous$$onoBehaviour instantiated in the scene returns this error:
$$anonymous$$issingReferenceException: The object of type '$$anonymous$$yClass' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
For the same reason the equality operator is able to return true when compared to null. It's because all objects that exist in the scene, including GameObjects and all components, have both a managed version (a version in C#) and an unmanaged, native code version that exists inside the engine. When you get a $$anonymous$$issingReferenceException, it is because you are attempting to access an object that still exists in managed memory (because you retained a reference to it in C#, so the garbage collector hasn't de-allocated it yet), but which was de-allocated in the unmanaged part of the engine.
This typically occurs when you call Object.Destroy on something to destroy it in unmanaged memory, and then try to access the object's properties afterwards.
Although I still don't know what causes this problem in my script, at least I understand what may be causing it. Thanks!
Problem solved, my script was subscribed to an event declared in ScriptableObject asset file. After entering play mode, the script was rebuild but the asset file still hold a reference to previous script instance. What I had to do was to unsubscribe from event in OnDisable().
Cool, that sounds like it might've been a tough one to crack. Glad you got it working. :)