How to Destroy a GameObject when the player looks away

I have a bunch of cubes and an Object that is shaped like the outline of a cube.

Right now I have a ray returning what object the player is looking at. If that object changes and is a cube I need to first destroy the old outline and then instantiate a new outline around the current cube. My code looks something like this:

Ray ray = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit)){
           if (hit.transform.tag == "Cube"){
				
				
				if (hit.collider.gameObject != current){
					if (current != placeHold) {Destroy(outline);}
					current = hit.collider.gameObject;
					Instantiate(outline,current.transform.position,current.transform.rotation);
				}

The line I’m having trouble with is the “Destroy(outline)” bit. I need to destroy the old outline before instantiating the new one, but currently it gives an error that looks like it’s trying to destroy the asset itself and not the clone that was instantiated.

Thanks!

From your code, it seems that outline is the outline prefab - don’t destroy it! Get a reference to the current outline when you instantiate it, and destroy this object instead:

// Declare this variable outside any function!
GameObject curOutline; // holds the current outline reference

  ...
  Ray ray = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
  RaycastHit hit;
  if (Physics.Raycast(ray, out hit)){
    if (hit.transform.tag == "Cube"){
      if (hit.collider.gameObject != current){ // not the current object:
        // destroy the current outline, if any:
        if (curOutline) Destroy(curOutline);
        current = hit.collider.gameObject; // save reference to the current object
        // save a reference to the newly created outline:
        curOutline = Instantiate(outline, current.transform.position, current.transform.rotation) as GameObject;
      }
    }
  }

NOTE: I’m assuming here that outline is a GameObject reference!