Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Check if an object is not null and has member at the same time?

Discussion in 'Scripting' started by hypnoslave, Dec 18, 2019.

  1. hypnoslave

    hypnoslave

    Joined:
    Sep 8, 2009
    Posts:
    436
    Hey guys, I use this pattern all the time, and it has the stench of me being an idiot and not knowing a better way.

    Basically I want to check if an object is null, OR if some flag is present in the object. The only way I know how to do this is to create a bool and do a series of checks, like so:

    Code (CSharp):
    1.  
    2. i = g.GetComponent<MyInterface>() as MyInterface;
    3. bool pass = false;
    4. if(i!= null)
    5. {
    6.      if (i.someFlagINeedToCheckIsTrue || MyConditionsAreCorrect())
    7.             pass = true;
    8. }
    9. if(pass){ DoSomeShit();}
    10. else {DoSomeOtherShit();}
    11.  

    Is there a way of just saying:
    Code (CSharp):
    1.  
    2. if(i != null && (i.someFlagINeedToCheckIsTrue || MyConditionsAreCorrect()){
    3.  
    ... or something simpler, without a null reference exception?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,773
    Yes, you can do exactly what you wrote and it won't create a null reference exception.

    C# (and all the other similar languages) do something called short-circuiting. If you have the line you wrote, it will first check if i != null. If the first line comes out to "false", and the next chunk is behind a && operator, it doesn't even bother - nothing on the other side of that operator could make it true. (The same thing happens if the first chunk comes out to "false" and there's a || operator - nothing on the other side of that operator could make it false) So it doesn't even run the code.
     
    hypnoslave likes this.
  3. hypnoslave

    hypnoslave

    Joined:
    Sep 8, 2009
    Posts:
    436
    lol wut.

    HAH I didn't even try it. that's funny.

    Thanks StarManta, that makes sense.