- Home /
Why does put RaycastHit2D type to boolean variable in 2D platformer Demo?
I study 2D tutorial from Official 2D platformer which is downloaded from asstes store.In the playercontrol script, i am confused with some codes , like the following picture:
the grounded is a bool type , the Physics2D.Linecast should return RaycastHit2D type , why does the retuen value assigne to grounded that is a boolean type ? There is no compiler error . Is there something wrong with the demo code ? any one can help me ?
Answer by Tehnique · Jul 10, 2014 at 06:17 AM
RaycastHit2D has an implicit conversion to bool. You can say "if(hits){...}" where hits is RaycastHit2D.
Here they say "RaycastHit2D implements an implicit conversion operator converting to bool which checks this property allowing it to be used as a simple condition check for whether a hit occurred or not.".
you are right . With your guidance. i find the implicit source code as follow:
public static implict operator bool(raycasthit2D hit)
{
return (object)hit.collider !=(Ojbect)null;
}
then, i find other use this conversition ,like transform ... This problem has troubled me one day since last night. Thank you very much!