How to do something when an object is in the player sights.


I will describe my question as follows.

Lets say that my first person controller has a crosshair. I want to do something of the sort:

if(player is looking at object && player is within certain distance)

Wich functions could I use to do something like this?

You only need one function: Raycast. It is discussed extensively on this site, in tutorials, and elsewhere on the web.

public GameObject playerCamera;
publich float threshold = 10f;

void Update() {
     Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
		RaycastHit hit = new RaycastHit();
     if(Physics.Raycast(ray, out hit, 1000f) {
          if(Vector3.Distance(playerCamera.transform.position, hit.point) < threshold) {
               Debug.Log("Object " + + " is within threshold.");