I use the following to detect if something is in front of my avatar:
void Start()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, hit,10) && hit.collider.gameObject.tag == "police" )
{
// do stuff here
}
Note that you need to set the tag of the gameObject from the editor. you could also use gameObject.name .
The last answer doesn't take into account that things can actually block the raycast from even reaching your desired object.
You must first give the object you want to detect a custom layer.
Then you have to shoot a raycast which will penetrate and ignore all layers except for the desired one, like so:
Please note: This example assumes you used custom layer #9:
float distance = 10;
int layer = 9;
int layerMask = 1<<layer;
if (Physics.Raycast(transform.position, fwd, distance, layerMask))
Debug.Log("Something in front");
You really shouldn't mark answers as accepted unless they have actually solved the problem, because questions with answers marked as accepted receive substantially less attention from people who would otherwise potentially be able to solve it for you.