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");
}
*/
}
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");
}
}