Physics Ray hit On/Off

hi,

i want the Enemy send out a Ray. If Player is in reach = attack. If not = idle.

Somehow it recognize the Hit, but not the NoHit.
The Boolean dont turn Off and stay On all the time, even when the player is not any more within the ray.

someone have an idea what i am doing wrong?
Thank you for your time, i appreciate it.

void Update ()
    {


        RaycastHit hit;
        Ray sendingRay = new Ray (transform.position, transform.forward);


Debug.DrawRay (transform.position, transform.forward *raylength, Color.green);

     

        if (Physics.Raycast (sendingRay, out hit, raylength))
        {
            if (hit.collider.tag == "Player")
            {
                wasHit = true;
                Debug.Log ("Hit");
            }

            if (hit.collider == null)
         
            {
                wasHit = false;
                Debug.Log ("NoHit");
            }
     
/*
Tried it also with

else
{
   wasHit = false;
    Debug.Log ("NoHit");
}
*/

        }

just do else. You probably have other colliders you are hitting when you dont hit the player, that’s why it never equates to null.

thank you for your respone.
I tried it with else already, but it just stop the wasHit noticing in the console , but dont set it as false somehow.

if i run into the ray it becomes true, but if i run out of it then it is still true. With setting to ==null or else, same result.

it is such a simple script, i really dont know why it is not working. :rage::hushed:

You should set it to false if you don’t hit anything with a raycast.
“NoHit” is inside the if block of raycast hitting something. If it doesn’t hit anything (your character is not within the raycast reach, for example), the method ends and doesn’t change the state of wasHit at all.
Do else block for the raycast if. Like so:

void Update ()
    {


        RaycastHit hit;
        Ray sendingRay = new Ray (transform.position, transform.forward);


        Debug.DrawRay (transform.position, transform.forward *raylength, Color.green);

   

        if (Physics.Raycast (sendingRay, out hit, raylength))
        {
            if (hit.collider.tag == "Player")
            {
                wasHit = true;
                Debug.Log ("Hit");
            }

            if (hit.collider == null)
       
            {
                wasHit = false;
                Debug.Log ("NoHit");
            }
        }
       else
       {
          wasHit = false;
           Debug.Log ("NoHit");
       }
}