I am trying to write a script to put on my enemies, which will use ray casting to identify if the player is within range.
I currently have a working ray casting system, however it does not discriminate between my player and other objects. Is there a way to check the tag of the object the ray is hitting?
void enemySight()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
Vector3 forward = transform.TransformDirection(Vector3.forward) * 20;//For testing
Debug.DrawRay(transform.position, forward, Color.green);//For testing
//If enemy contacts an object (ie player)
if (Physics.Raycast (transform.position, fwd, 20) && tag == "Player")//the 2nd condition is not working
{
//Do something
}
}
When I try implementing it like this, my enemy stops moving once the ray hits the player, and I get a NullReferenceException: Object reference not set to an instance of an object at line 9 of the code above ^^^