2D Raycasting problem

Hey, this is the first time I am using recasting and I have an error. I read some docs and watched a couple you tub videos. I am trying to get the distance from the origin of the recast to the . Once I get the distance I need to move the origin object to the PolyCollider2D transfer.Position. I am getting this error that is in the photo. First time trying to use Raycast and trying to understand it.

public class rayCastScript : MonoBehaviour {
    public GameObject rayBackStartLoc;


    void Update () {
        RaycastHit2D rHit;

        Vector2 castleBackVec2 = new Vector2(rayBackStartLoc.transform.position.x, rayBackStartLoc.transform.position.y);
        Vector2 downDirection = new Vector2(0, -1);

        // draw a green line to test the debug
        Vector3 backCheck = transform.TransformDirection(Vector3.down) * 1000;
        Debug.DrawRay(rayBackStartLoc.transform.position, backCheck, Color.green);

        if(Physics2D.Raycast(castleBackVec2, downDirection)){
            print(rHit.distance + " " + rHit.collider.gameObject.name);
        }
    }
}

Thanks for any help!

Physics2D.Raycast() is structured slightly differently from the Physics.Raycast() call.

In the 2D version, you get back the RaycastHit2D object you want. And you ALWAYS get one back.

In your code you are just testing it for true/false, and as a consequence of UnityEngine.Object overloading its null check, your code partially works: you are saying in essence, “do this if the RaycastHit2D is nonzero.” Since it is a struct, it will ALWAYS hit, and since you don’t assign it, there you are!

So look at the sample snippet in the above reference. It looks like you are supposed to check the .collider property for being non-null in order to know if it hit.

Thank you! I did a list more testing and reading today and figured out a simple solution.

public float rangeFindFront(){
        Vector2 castleFront = new Vector2(rayFrontLoc.transform.position.x, rayFrontLoc.transform.position.y);
        RaycastHit2D hitF = Physics2D.Raycast(castleFront, Vector2.down);
        float distance = 0;
        if (hitF.collider != null) {
            distance = Mathf.Abs(transform.position.y - hitF.point.y);
        }
        return distance;
    }