Change Variable on Raycast Hits something else?

I have blocks where they highlight when hit, but I’m struggling to figure out on how to turn off the highlighting after I’m no longer looking at the block.

For example: You approach a chest, it highlights blue. Then when you back away it returns to normal.

Here’s what I have so far:

using UnityEngine;
using System.Collections;

public class Interaction : MonoBehaviour {

    // Update is called once per frame
    void Update () {
        Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f,0.5f,0f));
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 3)){

           if (hit.transform.gameObject.tag == "Block") {
                hit.transform.gameObject.GetComponent<BlockStats>().Highlight();

                if (Input.GetKeyDown(KeyCode.E)) {
                    hit.transform.gameObject.GetComponent<BlockStats>().RemoveHealth(50);
                }
           } 
        }
    }
}

and the script that gets called…

using UnityEngine;
using System.Collections;

public class BlockStats : MonoBehaviour {

	public int Health = 100;
	public bool isHighlighted;
	public Material highlightMaterial;
	public Material startMaterial; 
	
	void Start () {
		startMaterial = gameObject.GetComponent<Renderer>().material;
	}

	public void Highlight () {
		gameObject.GetComponent<Renderer>().material = highlightMaterial;
		Invoke ("Unhighlight", 0.5f);
	}

	public void Unhighlight () {
		gameObject.GetComponent<Renderer>().material = startMaterial;
	}

	public void RemoveHealth (int dmg) {
		Health -= dmg;
		if (Health <= 0) {
			gameObject.SetActive(false);
		}
	}

}

Thanks for the help. Probably overthinking this.

Solved the problem myself, a bit of recoding was required.

Here’s a Link to a GitHub Download

or just copy and paste:

using UnityEngine;
using System.Collections;
 
public class Interaction : MonoBehaviour {
 
    // Update is called once per frame
    GameObject obj;
	public Material startMat;
	public Material highlightMat;

    void Update () {
        Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f,0.5f,0f)); 
		// Change the Vector above to Input.mousePosition for wherever your mouse is instead of the middle of your camera.
        RaycastHit hit;

		if (obj != null) {
			obj.GetComponent<Renderer>().material = startMat;
			obj = null;
		}

        if (Physics.Raycast(ray, out hit, 1000)){
 
            if (hit.transform.gameObject.tag == "Block") {
                obj = hit.transform.gameObject;
				startMat = obj.GetComponent<Renderer>().material;
                
                if (Input.GetMouseButtonDown(0)) {
					obj.GetComponent<Renderer>().material = highlightMat;
                }
            } 
         }
     }
 }