0
\$\begingroup\$

Pretty much as the title asks, why is this code possible?

if (Physics2D.Raycast(...)) {

}

even though the method itself returns RaycastHit2D?

\$\endgroup\$
2
\$\begingroup\$

The answer to questions about the Unity API can generally be found in the docs:

RaycastHit2D implements an implicit conversion operator converting to bool which checks [the collider] property allowing it to be used as a simple condition check for whether a hit occurred or not.

What this means is that the RaycastHit2D structure's code looks something like this under the hood:

public struct RayCastHit2D {
    public Collider2D collider;

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

This says to the compiler "wherever you see a RaycastHit2D used like a boolean, you can automatically convert it by running this method (which returns true if there was a collider hit, and false otherwise), without requiring the user to type out the cast or comparison explicitly.

\$\endgroup\$
  • \$\begingroup\$ Thank you sir. This now makes perfect sense! \$\endgroup\$ – FICHEKK Dec 2 at 20:17
  • \$\begingroup\$ Heh looks like I missed that part! \$\endgroup\$ – Vaillancourt Dec 2 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.