Player moving out of raycast

I have a basic raycast coming off of an enemy. It’s only purpose is to detect whether the player is there or not. It is set up in the animator to trigger with certain states. If it detects the player, it switches a boolean to true and it moves to another state. That part all works perfectly fine. The problem I’m having is switching that boolean back to false. What I want to happen is that when the player is no longer detected by that raycast, it then triggers the boolean to false. Here is the code that I currently have.

{
    RaycastHit hit;
	Ray detect = new Ray(animator.transform.position, animator.transform.forward);

	Debug.DrawRay(animator.transform.position, animator.transform.forward * rayLength);
	
	if(Physics.Raycast(detect, out hit, rayLength))
	{
			if(hit.collider.tag == "Player")
			{
				animator.SetBool("Alert", true);
			}
			else
			{
				animator.SetBool("Alert", false);
			}
	}
}

To me, it looks as if it should work. It’s checking if it collides with the player, and if it doesn’t then it sets it to false. There’s no errors or anything. It just simply doesn’t work. Can you perform an action with an empty raycast, or does it actually need to be detecting something?

you will need to set it to false when you have no raycast hit at all as well:

     if(Physics.Raycast(detect, out hit, rayLength))
     {
             if(hit.collider.tag == "Player")
             {
                 animator.SetBool("Alert", true);
             }
            else 
           {
                    animator.SetBool("Alert", false);
            }
     }
     else 
     {
            animator.SetBool("Alert", false);
     }

Try this:

{
     RaycastHit hit;
     Ray detect = new Ray(animator.transform.position, animator.transform.forward);

     Debug.DrawRay(animator.transform.position, animator.transform.forward * rayLength);
     
     if(Physics.Raycast(detect, out hit, rayLength))
     {
             if(hit.collider.tag == "Player")
             {
                 animator.SetBool("Alert", true);
                 return;
             }
     }
      animator.SetBool("Alert", false);
 }

On if statements, if the final thing you want to happen turns true in the middle of a block of code, just return back at each final true moment, and then add all the false statements below that.

After some playing around, I found the issue. It seems to be a problem with Unity. I experimented with variations of the code, including both of what you guys offered, and it still didn’t work. Then I changed the exit time of the transition and it works now.

I was giving it an exit time of 2 and then it would transition to a new state. The transitions I was using that switched the boolean to true didn’t have an exit time. For some reason when trying to run a condition with an exit time of 2, it just doesn’t work. Changing the exit time to 1 allows the condition to trigger. That seems like a glitch in Unity.

Anyway, thanks for the help.