Why is a non-null RaycastHit2D read as "True" by an if statement?

Ok, so if I cast a 2D ray and want to use the RaycastHit2D … for example, using the code below:

targetHit = Physics2D.Raycast (transform.position, new Vector2 (0, -1));

if (targetHit) {
        Debug.Log ("Hit!”);
    } else {
        Debug.Log ("No hit");
    }

I understand that the if condition could be (targetHit != null) and that is clear.

Why is it that the (targetHit) is read as “True” when it is not empty/null?

Is this analagous to other programming languages like Python where:

  1. A default zero integer is False, but any other number is True
  2. A default empty String is False, but any other string is True

… example … (in Python3)
if “test”:
print(“True”)
else:
print(“False”)

Actually it could not be. RaycastHit2D is a struct and therefore can’t be null. Also, null does not evaluate to false in any case. The reason “if (targetHit)” works is because the RaycastHit2D struct contains this code:

public static implicit operator bool (RaycastHit2D hit)
{
    return hit.collider != null;
}

–Eric

1 Like