I use the following to detect if something is in front of my avatar:
void Start()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 10))
Debug.Log("Something in front");
}
Now, I am trying to find out if only a specific object is in front, for example another avatar with the name Police
in the hierarchy:
public class CharAnim : MonoBehaviour
{
police = GameObject.Find("Police");
void Start()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 10))
Debug.Log("Something in front");
}
}
However, from the documentation, I cannot see if it is possible to use this police
variable to detect it through ray-casting, measuring distance to it, etc...
How do I implement this?
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:
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.
Note that you need to set the tag of the gameObject from the editor. you could also use gameObject.name .