How do I change the raycasthit material back?

I am dealing with raycasting in the middle of the screen. I want to change the material of the hit object only when the raycast is hitting it.

I created an empty gameobject (dummie) to store the hit object in it.

I then changed the color when the raycast hits the object. The problem is that it changes the color of all the objects touched if the raycast is always hitting something. I need to change the color of the material back if I am not hovering over it.

I know exactly what causes the problem: the gameObject stored in the “obj” is left with its new material and the new one that replaces it has the new material. I need to access all the materials with the same new material and only affect the one that I am currently hovering over.

Here is the part of the code which has the problem:

public Material newMtl;
public Material oldMtl;

void update(){
if(Physics.Raycast (vct, fwd, out hit)){
obj = hit.collider.gameObject;
obj.GetComponent().material = newMtl;
}else{
obj.GetComponent().material= oldMtl;
}
}

Please format your code by highlighting it and clicking the ‘101010’ button, as it says in the user guide on the right. Makes it much easier to read, as well as not losing stuff inside angle brackets.

After the raycast, but before you set the obj value, check to see if it’s different than the hit object. If it’s different, reset the obj’s material, then set obj to the new hit target. This also avoids it constantly trying to set the material of the object it’s pointed at.

You also need to make sure obj is not null before changing its value in the else section or you’ll get a Null Reference Exception right from the start if not pointing at anything.

using UnityEngine;
using System.Collections;

public class TestScript : MonoBehaviour
{
	public Vector3 vct;
	public Vector3 fwd;
	RaycastHit hit;

	GameObject obj;
	Renderer objRenderer;
	public Material newMtl;
	Material oldMtl;

	void Update()
	{
		if(Physics.Raycast (vct, fwd, out hit))
		{
			if(obj != hit.collider.gameObject)//If we're not pointing at the previous target
			{
				if(obj != null)//If previous target is set, reset its material
				{
					objRenderer.material = oldMtl;
				}
				
				obj = hit.collider.gameObject;//Store reference of target to a variable
				objRenderer = obj.GetComponent<Renderer>();//Get targets Renderer
				oldMtl = objRenderer.material;//Store targets current material
				objRenderer.material = newMtl;//Set target to new material
			}
		}else{//If we're not pointing at anything
			if(obj != null)
			{
				objRenderer.material = oldMtl;//Reset targets material
				obj = null;//Clear reference
			}
		}
	}
}

I also have it store the Renderer of the target to reduce GetComponent() usage, as it’s a slow operation. Finally, I have it set oldMtl to the targets material, so targets can have different materials if you want.