Raycast hit Not Set to an instance object

I’m trying to get an enemy to turn around when a wall is in front, for which I set a raycast to detect if the collider name was a wall. When trying to test the code, it shoots the error “Object reference not set to an instance of an object”. I don’t see the problem.

here is the code

void WallDetection()
        RaycastHit2D wallRay = Physics2D.Raycast(wallDetect.position, Vector2.right, 4f);
        if (wallRay.collider.name == "Wall Right")
            moveRight = false;

        else if (wallRay.collider.name == "Wall Left")
            moveRight = true;

you need to confirm you actually hit a collider (before you check it’s tag)

    if (wallRay.collider != null)

as shown in the example on this page:

If your wallRay doesn’t end up colliding with anything, it will cause your program to crash. You can prevent this by checking if wallRay = null, or replacing the instantiation with the following:

RaycastHit2D wallRay; if(Physics2D.Raycast(wallDetect.position, Vector2.right, out wallRay, 4f){ //if the raycast hits something, do the following... }

hope that helps!