Can an object tell when a raycast is hitting it?

I am trying to make it so when I look at an object it activates a script on the gameobject it hits and when I look away it deactivates the same script, but I don’t know how to communicate to the gameobject with the script that I am no longer looking at it.

using HoloToolkit.Unity.InputModule;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OnGazeUnitSelection : MonoBehaviour {


    public Transform cam;
    public static GameObject unitSelected;

	
	void Start () {
        cam = Camera.main.transform;
        
    }
	
	
	void FixedUpdate () {

        RaycastHit hit;

        Ray camRay = new Ray(cam.position, cam.forward);



        if(Physics.Raycast(camRay, out hit)){

            Debug.DrawLine(transform.position, hit.point, Color.cyan);
            unitSelected = hit.transform.gameObject;
            Debug.Log(unitSelected);
            hit.transform.gameObject.GetComponent<HandDraggable>().enabled = true;
        }
        else
        {

            ???
        }



	}
}

So you’re already caching the object you’ve last selected. When your raycast doesn’t hit, all you need to do is access the cached object and do something. I’ve modified the else clause of your raycast logic to demonstrate.

using HoloToolkit.Unity.InputModule;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class OnGazeUnitSelection : MonoBehaviour {
    public Transform cam;
    public static GameObject unitSelected;

    void Start () {
        cam = Camera.main.transform;
    }
     
    void FixedUpdate () {
        RaycastHit hit;
        Ray camRay = new Ray(cam.position, cam.forward);
 
        if(Physics.Raycast(camRay, out hit)){
            Debug.DrawLine(transform.position, hit.point, Color.cyan);
            unitSelected = hit.transform.gameObject;
            Debug.Log(unitSelected);
            hit.transform.gameObject.GetComponent<HandDraggable>().enabled = true;
        }
        else
        {
            if (unitSelected && unitSelected.GetComponent<HandDraggable>())
            {
                unitSelected.GetComponent<HandDraggable>().enabled = false;
                unitSelected = null;
            }
        }
    }
 }

Setting unitSelected to null prevents the else clause body from executing every frame, which is useful if what you want to do is more involved than just simply disabling a script.

First of all, I advise you to include a check, whether or not the object can be dragged or not (i.e. if it has that script-component on it, or has a specific tag).

Also, as you already cache the object your raycast is hitting, I would do it like this:

else
{
	if (unitSelected != null)
	{
		unitSelected.GetComponent<HandDraggable>().enabled = false;
		
		unitSelected = null;
	}
}