Change material on raycast hit?

Hello all! I was wondering how I’d go about changing an objects material when said object gets by the player’s raycast. I already have a script on the player for raycasts, and a script on the object that can change the material, etc. Can anyone point me in the right direction?

void callChangeMat()
{
RaycastHit hit = new RaycastHit ();
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 5000)) {
if (hit.transform.tag == “you can add the tag here if need be”) {

			//make sure the change matereial script is attached to the object hit.
			//make sure the ChangeMatFunction is set to public
			hit.transform.GetComponent<yourScriptName> ().ChangeMatFunction ();
		}
	}
}

@DrDoobie

So I tested these scripts and got a good output so hopefully you can adjust it to your needs.

First the shoot script:

public float range = 50;
        public Camera cam;
        public float damage;
        public GameObject shotHitParticle;
    
        void Update()
        {
            if (Input.GetButtonDown("Fire1"))
            {
                GunShot();
            }
        }
    
        void GunShot()
        {
            RaycastHit hit;
            if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, range))
            {
                // The farm components are what I named the material change script
                // So remember to replace that part of the script with the name of
                // your second script.
                if (hit.collider.GetComponent<Farm>() != null)
                {
                    hit.collider.GetComponent<Farm>().materialChange(hit.collider.GetComponent<Renderer>());

                    Instantiate(shotHitParticle, hit.point, hit.collider.transform.rotation);
                }
            }
        }

The Color Change Script:

    public Material[] material;
    [HideInInspector] public Renderer rend;
    
    // Use this for initialization
    void Start()
    {
        rend = GetComponent<Renderer>();
        rend.enabled = true;
        rend.material = material[0];
    }

    // Update is called once per frame
    public void materialChange(Renderer render)
    {
        render.material = material[1];
    }

If you find a problem feel free to comment :smiley: