How to trigger scripts with line sight. (3D & First-Person)

As of now, I’m able to pick up items with a spherical collider that is on trigger.
I wonder if it’s possible that I can also check if my character’s facing the item before the character can actually pick it up.

I tried looking up onto it and saw something about “Raycast” or if that’s what it’s called. I wanted to ask first what would be the best approach to do.

Thanks in advanced guys! :slight_smile:

Likely you will need to use a raycast, sort through what was hit, and base your code on the result.

Raycast hits = Physics.RaycastAll () //from camera to object (forward)

foreach (Raycast hit in hits)
{
    if (hit.gameobject.tag == "Item") //or layer
    {
        hot.gameobject.GetComponent <ScriptTriggerScript >().EnableMyTriggerScript ();
    }
}

public void EnableMyTriggerScript ()
{
    myScript.SetActive (true);
}

This is just an example. You could find only the nearest object, the furthest, the first hit, the last hit, all hit (store the hits, then iterate through that list to do logic).

And you dont necessarily need a function like EnableMyTrugherScript. If all gameobjects tagged “Item” used the same scripts, or all gameobjects used a specific script, you could handle it that way.

The idea is…

  1. Check what colliders are infront of the camera. (Center of camera)
  2. Make sure youre hitting the correct objects, for example not the ground collider or uninteractable object.
  3. Once you find the object, do some logic. i.e. Disable the script.