Turning off a script when Raycast leaves object

Hi Folks,

So i’m having some difficulty with Raycasts and turning on and off scripts depending on whether the ray hits within a certain distance.

Currently my script highlights the object by changing the material color when within a certain distance (pick-up distance), but I also want it to turn on a script on the object, and then turn it off when the Raycast is no longer colliding.

Any help would be great, as it can currently turn the script on, but crashes when leaving the object (where it should turn off).

Thanks!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HighlightObjects : MonoBehaviour {

	public float highlightrange;
	public string ObjectIdent;
	private Color highlight;
	Material originalmat, tempmat;
	Renderer render = null;
	PickUpCode pickupcode;

	// Use this for initialization
	void Start () {
		highlight = Color.black;

	}
	
	// Update is called once per frame
	void Update () {
		RaycastHit hitInfo;
		Renderer currentrender;


		Debug.DrawRay(this.transform.position, this.transform.forward * highlightrange, Color.blue);


		if(Physics.Raycast(this.transform.position, this.transform.forward, out hitInfo, highlightrange)){
			currentrender = hitInfo.collider.gameObject.GetComponent<Renderer>();
			pickupcode = hitInfo.collider.gameObject.GetComponent<PickUpCode>();

			if (currentrender == render)
			return;

			if (currentrender && currentrender != render){
				if (render){
				render.sharedMaterial = originalmat;
				}
				}
				if(currentrender)
				render = currentrender;
				else
				return;

				originalmat = render.sharedMaterial;

				tempmat = new Material(originalmat);
				render.material = tempmat;
				render.material.color = highlight;
				pickupcode.enabled = true;
				}
				else{
				if(render){

				render.sharedMaterial = originalmat;
				render=null;
				pickupcode = hitInfo.collider.gameObject.GetComponent<PickUpCode>();
				pickupcode.enabled = false;
				}
		}

	}
}

Managed to answer my own question! Essentially had to save the last hit object as a public variable, then use that to turn off the script when the raycast left it.