Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Null checking works differently for classes derived from UnityEngine.Object #148

Closed
SirIntruder opened this issue May 9, 2017 · 3 comments
Milestone

Comments

@SirIntruder
Copy link

SirIntruder commented May 9, 2017

Resharper reports 'this != null' as an error, but really it shouldn't if class is derived from UnityEngine.Object.
This happens often when you work with callbacks, something like

public class MyBehaviour : MonoBehaviour
{
  void Start()
  {
    MyInvoker.InvokeAfterSecond(() => 
    {
       // scene gets changed in the meantime, MyBehaviour is now gone 
       // transform getter will throw NPE if this doesn't get checked
        if (this == null) return; 
        transform.position = x;
    });
  }
}

btw if somebody knows of a nicer way of checking this do tell me. No unity property (as in gameObject getter) seems to work , they all throw NPE.

@nkAlex
Copy link

nkAlex commented May 9, 2017

Yeah, this is one of Unity's peculiar behaviours, it can happen when a GameObject has been destroyed by Unity (in native code), but the MonoBehaviour script is still referenced somewhere and therefore hasn't been garbage collected. In this case none of Unity's built-in properties and methods will work throwing a NullReferenceException, and a this == null check is the only way to determine if an object is dead or alive (it actually calls to the native code to check the object) and is totally valid for Unity, though makes no sense for C# :)

@CAD97
Copy link

CAD97 commented May 9, 2017

Here's an old blog post on the issue (couldn't find a newer source): https://blogs.unity3d.com/en/2014/05/16/custom-operator-should-we-keep-it/

EDIT: found this: https://forum.unity3d.com/threads/unitys-custom-operator.316222/

@citizenmatt
Copy link
Member

Rider 2017.3 no longer suggests to convert to ?? or ?., and Rider 2018.1 will have a warning if you try and use these operators on a type deriving from UnityEngine.Object.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants