Having problems changing the material of current target.

I’ve created a basic targeting system using RayCasting by using the Scripting Reference and I’m trying to set the target to a different color, currently this is working. Although, I would like to make it so that ONLY the current target has the color, which is “Red”. When the target is De-Selected and another target is selected, I would like for it to go back to it’s original color and turn the new target red. Not sure how to go about the reverting.

using UnityEngine;
using System.Collections;

public class RaycastTargetting : MonoBehaviour {
	RaycastHit hit;
	Ray ray;
	public Transform target;
	
	void Update (){
	  	if (Input.GetButton("Fire1")){
	    	ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	    	if (Physics.Raycast (ray, out hit, 250)){
	      		if (hit.transform.tag == "NPC"){
	        		target = hit.transform;
					ApplyTarget(target);
	      		}
	   		 }
	  	}
	}
	
	void ApplyTarget(Transform theTarget) {
		  theTarget.renderer.material.color = Color.red;
	}
}

You could do it by having a variable, where you store the last selected target. Then once you select a new target, you revert the last targets material to its normal color. Change the newly selected target to Red and assign it then to the variable, that you store the last selected target :slight_smile:

@Sillydan solution is correct, however it would be better to store the original sharedMaterial and assign that back. Otherwise the material will be duplicated and it will break dynamic batching.

I would do something like that:

public class RaycastTargetting : MonoBehaviour
{
    public Transform target = null;
    private Material m_OldMaterial = null;
    void Update ()
    {
        if (Input.GetButton("Fire1"))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast (ray, out hit, 250))
            {
                if (hit.transform.tag == "NPC")
                {
                    SetTarget(hit.transform);
                }
            }
        }
    }

    void SetTarget(Transform newTarget)
    {
        if (target != null && m_OldMaterial != null)
        {
            target.renderer.sharedMaterial = m_OldMaterial;
        }
        target = newTarget;
        if (target != null)
        {
            m_OldMaterial = target.renderer.sharedMaterial;
            target.renderer.material.color = Color.red;
        }
    }
}