I want to have an eyeball that when the player looks at, it disappears by moving to the side. Like in a horror game. I know how to make the object move to a set location but I don't know how I would make the object do the action when the player looks at it.

Help would be appreciated.

  • \$\begingroup\$ Do you know how to detect when something is in the field of view of a camera? \$\endgroup\$
    – Questor
    May 4, 2023 at 21:18
  • \$\begingroup\$ I've watched a tutorial on it, so only a bit of basic knowledge. \$\endgroup\$
    – Dawid
    May 4, 2023 at 21:23
  • 1
    \$\begingroup\$ What specific knowledge do you have? This is important to document in your question, so that answers can focus on giving you the knowledge you don't already have, instead of repeating knowledge you do \$\endgroup\$
    – DMGregory
    May 5, 2023 at 1:48

1 Answer 1


"The object the player looks at" is functionally identical with "the object the main camera points at".

So you can just use a Physics.Raycast from the camera into the scene, check if the object that is hit by the ray is the one you want, and if so cause it to do a reaction.

This script assumes that it is on the active camera. If you want to put it on a different object, replace transform with Camera.current.transform. It also assumes that the eyeball has a Collider of appropriate size and shape. This script also assumes that the eyeball has an unique script on it named "YourEyeballScript". Yours is probably named differently, so you need to change the name of the script accordingly. Or if you don't have any unique script on it, you could create an empty one as a marker-component.

// do the raycast
RaycastHit hit;    
if (Physics.Raycast(transform.position, transform.forward, out hit))
    // if we hit an object, check if it is the "Eyeball" by checking 
    // if it has the script that is on the eyeball
    YourEyeballScript eyeball;
    if(hit.collider.TryGetComponent<YourEyeballScript>(out eyeball)) {
        // We are looking at the eyeball. Make the eyeball do The Thing!

If the raycast fails to detect the object, then I recommend to read the documentation of Physics.Raycast I linked above. The method has optional parameters that might or might not be required in your case, depending on how your scene is set up and how you are using layers in it.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .