Detect when object is no longer hit by Raycast

Hi All,

At first this seem like a simple idea, but I can’t seem to figure out how to do it.

I have a raycast, and when it hits an object with tag “key”, it sets a boolean in script on that object to TRUE. Easy.
What I’d like is for when the the raycast stops hitting that same object, the boolean reverts to FALSE.

Here’s what I got so far, amongst many other bizarre attempts.

 private bool Key;

 public Camera camera;
 
 void Start() {
    	camera = GetComponent<Camera>();     
    }
    
    void Update() {
        Ray ray = GetComponent<Camera>().ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        RaycastHit hit;   
 {
 if ((Physics.Raycast(ray, out hit, 100)) && (hit.collider.tag == "Key"))
 {
		Key = hit.collider.gameObject.GetComponent<Activated>().active;
        Key = true;
 }
 else if (Key != null)
 {
     Key = false;
 }
 
}
}

}

Try swapping your update to this.

void Update() 
	{
		Ray ray = GetComponent<Camera>().ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
		RaycastHit hit;   
		{
			if (Physics.Raycast(ray, out hit, 100))
			{
				if(hit.collider.tag == "Key")
				{
					Key = hit.collider.gameObject.GetComponent<Activated>().active;
					Key = true;
				}
				else
				{
					// Hitting something else.
					Key = false;
				}
			}
			else if (Key == true)
			{
                // not anymore.
				Key = false;
			}
		}
	}

This will ensure that the Key bool will get set to false in either of the two cases:

  1. We didn’t hit anything, therefore we didn’t hit the key.
  2. We hit something that isn’t the key, therefore we aren’t hitting the key.

private bool hitFlag = false;

void Update()
{        
    if(Physics.Raycast(...))
    {
        hitFlag = true 
    }
    else if (hitFlag)
    {
        hitFlag = false;
        // there you go. here we have object hitted on previous frame but not on this frame.
    }
}