Raycast help: When a ray hits nothing

Hello Unity Community,
I decided to get rid of the old onMouseOver methods I was using and give Raycasting a shot. In the below code, the else statement wont run until the ray collides with something other than the tagged object. How do I run what is in the else statement if the ray is colliding with nothing after colliding with the object? For instance, if I look at the ground after the object, else runs just fine. If I look at the sky, it doesn’t, I assume because it’s not hitting a collider. I’m sure this is really a small beginners oversight but its always the small things that stump me for some reason.

void CloseRay(){
        RaycastHit hit;
        Ray myRay = Camera.main.ScreenPointToRay (Input.mousePosition);
        Debug.DrawRay(myRay.origin, myRay.direction * closeRayDistance, Color.green);

        if (Physics.Raycast (myRay, out hit, closeRayDistance)) {

            if(hit.collider.tag == "Object"){
                Debug.DrawRay(myRay.origin, myRay.direction * hit.distance, Color.red);
                GameManager.closeObjectHit = true;
                GameManager.targetBeingHit = hit.collider.gameObject.name;
                Debug.Log (GameManager.targetBeingHit);
            }else{
                Debug.DrawRay(myRay.origin, myRay.direction * closeRayDistance, Color.white);
                Debug.Log ("It's NOT hitting");
                GameManager.closeObjectHit = false;


            }
        }
    }

Many thanks in advance :slight_smile:

Right now, your code only checks if you hit an object tagged “Object” or if you hit an object not tagged “Object”.
Simply add an else statement to your raycast and do what you want to do if you hit nothing.

1 Like

Thank you kind sir,
I thought I tried that but in my 2am zombie like state, beginner oversights happen. That and the fact that i’m a beginner lol. Works as intended now. On that note, I’m bug free and able to go to sleep!
Thanks again.

Good to hear! Goodnight :slight_smile: