Easiest way to tell when an object is NOT struck?

This one’s been bugging me for awhile- So, its easy to rayCast an object, check if its being struck and then, say, change its shader so that its highlighted.

But whats the most efficient way to change it back? Is it simply to loop over every object in the scene? That seems crazy. Is it to set up a variable that turns itself false every frame and let the ray overwrite it? That also seems crazy.

I feel like there has to be an elegant solution I’m overlooking to have an object reset itself to “default”. Thoughts?

You CAN use raycast for this, but if all you’re doing is switching materials, I think it may be more efficient to use OnMouseOver and OnMouseExit to do this. Attach this script to the objects you wish to make highlighting possible when the mouse hovers over them. You define your highlight material in the editor, the original is called on Awake() so it can be stored.

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour
{
	public Material highlight;
	Material original;
	
	void Awake()
	{
		if(renderer)
			original = renderer.material;	
	}
	
	void OnMouseOver()
	{
		if(renderer)
			renderer.material = highlight;
	}
	
	void OnMouseExit()
	{
            if(renderer)
		        renderer.material = original;	
	}
}