Replacing material on object 'clipped' by Raycast and returning back to normal once 'unclipped'

I’ve been trying to get this to work for a while now
I have used various methods, the first I’ve used a simple SetActive(false), which doesn’t work with Raycast as the object isn’t visible to Raycast anymore.
And finally settled on changing the material of the object the raycast has clipped through, which works, but I can not fathom out how to change it back to it’s original material once the raycast isn’t passing through it anymore.

I feel like I’m on the tip of getting this, but have to start from scratch again.

The object is assigned:

    Material clippedMaterial;

which makes it transparent

I’ve had success with changing the objects visibility, material, instance, but it’s getting them back to the original state I’m having trouble with.

This is completely different to what I was hoping, but it works. I only have a small amount of things that need to have this on, so it’s -possibly- not that processor intensive (if anyone can confirm if doing this is?)

I haven’t optimised this and most of the public variables are just that to see what they’re doing. I hope this helps someone.

Attached to the object to be made transparent:

 using UnityEngine;
public class ObjectTransparencyController : MonoBehaviour {
     public Material _original;
     public Material _transparent;
     private GameObject player;
     private PlayerController pC;
     private Renderer rend;

    public Vector3 objectTransform;
    public Vector3 cameraTransform;
    public float cameraDistanceCalc;
    public float cameraDistanceCalcAdjuster; //to set correct distance between player and camera
    public float totalDistance;

    void Start()
     {
         player = GameObject.FindWithTag("Player");
         pC = player.GetComponent<PlayerController>();
         rend = this.GetComponent<Renderer>();
     }
     void Update()
     {
        objectTransform = transform.position;
        cameraTransform = Camera.main.transform.position;
        cameraDistanceCalc = (objectTransform - Camera.main.transform.position).sqrMagnitude - cameraDistanceCalcAdjuster;
        totalDistance = pC.Dist();

        //if ((objectTransform - Camera.main.transform.position).sqrMagnitude < pC.Dist())
        if (cameraDistanceCalc < totalDistance)
         {
             rend.material = _transparent;
         }
         else
         {
             rend.material = _original;
         }
     }
}

Included in your players controller script:

public class PlayerController : MonoBehaviour {

    public float distanceSquared;

//your variables ...

void Update()
{

        distanceSquared = (transform.position - Camera.main.transform.position).sqrMagnitude;

//your stuff ...

}

public float Dist()
{
       return distanceSquared;
}

http://www.labyrintheer.com/2017/07/20/how-to-see-your-player-making-walls-transparent/