Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Differentiate between 'null' and 'missing' references in script?

Discussion in 'Scripting' started by StarManta, Dec 28, 2015.

  1. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Is there a way to tell the difference in script between an object reference that's null (it has never been assigned) vs one that's missing (the object that was assigned has since been destroyed)? The default inspector can tell the difference - it says 'Null' or 'Missing' respectively - but how?
     
  2. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,732
    an object that has been destroyed can still have GetInstanceID() called on it, even though a null comparison equates to true (the equality operator for null is overridden I believe), could you use the GetInstanceID() result to differentiate how you want?
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    If I call 'unknown.GetInstanceID()', and unknown is null, that would throw an exception. I could wrap it in a try/catch, I suppose? So maybe something like this?
    Code (csharp):
    1.  
    2. bool IsMissingReference(UnityEngine.Object unknown) {
    3. try {
    4. unknown.GetInstanceID();
    5. return false;
    6. }
    7. catch (System.Exception e) {
    8. return true;
    9. }
    10. }
     
  4. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,732
    As I understand it, that ought to work, have you tried it?

    I was trying to find a blog post I read recently, which I thought you might find useful, where one of the devs was discussing their reasoning behind overriding the null equality operator, and why they probably wouldn't change it. But as usual I can't find it now :(
     
  5. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    I'd enjoy reading the reasoning behind overriding the equality operator, if you stumble across it again.
     
  6. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,732
  7. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    Code (csharp):
    1.  
    2. var b = object.ReferenceEquals(obj, null);
    3.  
    This method will actually test if null, as opposed to testing if destroyed.

    So it will return true if the thing is actually null, not just dead.