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

If Statements and GameObjects

Discussion in 'Scripting' started by unity_EMF_WQ1QgS9V3Q, Jan 22, 2020.

  1. unity_EMF_WQ1QgS9V3Q

    unity_EMF_WQ1QgS9V3Q

    Joined:
    Apr 29, 2019
    Posts:
    2
    Hey guys,
    I recently downloaded a package of the asset store. As I was reading the script in this package, I noticed that they used a gameobject as a condition for an if statement. I am a little confused on how this is achievable.
    Any answers?
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    SisusCo likes this.
  3. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,295
    The Unity devs have specifically enabled this behaviour with Objects by defining an implicit conversion operator from Object to bool.

    Specifically this code snippet found in the Object class makes it possible:
    Code (CSharp):
    1. public static implicit operator bool(Object exists)
    2. {
    3.     return !Object.CompareBaseObjects(exists, (Object) null);
    4. }
    Functionally speaking "if(gameObject)" is exactly the same as "if(gameObject != null)". Here's the code for the != operator:
    Code (CSharp):
    1. public static bool operator !=(Object x, Object y)
    2. {
    3.     return !Object.CompareBaseObjects(x, y);
    4. }
     
    Last edited: Jan 22, 2020
  4. unity_EMF_WQ1QgS9V3Q

    unity_EMF_WQ1QgS9V3Q

    Joined:
    Apr 29, 2019
    Posts:
    2
    Thanks guys for your answers. Didn't know this was possible but now I've learnt something new. Really appreciate it.
     
    SisusCo likes this.