How to use Raycasting 2D to mouse click and delete objects?

So I’m using the code below right now. The goal is to be able to click & destroy objects on screen with a mouse.

Right now I get this error: “Missing Reference Exception: The object of type ‘GameObject’ has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.”

I know this is because the destroy command isn’t specific enough but what should I be destroying? Or alternatively, I’ve heard about “pooling” objects and right now my spawner spawns the objects from a pool but how do I get rid of those objects upon clicking without destroying? Any help on this would be great.

using UnityEngine;
using System.Collections;

public class ClickTest : MonoBehaviour {
	// public GameObject red, red2, yellow, yellow2, MainCamera;
	// Use this for initialization
	
	public int health = 1;
	
	void Update () {
		if (Input.GetMouseButtonDown(0)) {
			Debug.Log("Pressed left click, casting ray.");
			CastRay();
		}       
	}
	
	void CastRay() {
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
		if (hit.collider !=null&&hit.transform==transform) {
			Debug.Log (hit.collider.gameObject.name);
			health --;
		}
		if (health <= 0) {
			Die ();
		}
	}
	void Die() {
		Destroy (gameObject);
		
	}
}

First: I assume your raycast does work? Is the Debug.Log showing properly?

Second: There is an error in your script. Die() destroys the clicker, not the target object. Attach the script to the camera. Change your code to something like (untested):

your destroyable gameobject needs to have a script attached to it, ideally with a public method DamageMe() for instance. If this script is named Destroyable, something like this can work:

...
// Script on the mouse
     if (hit.collider !=null) 
     {
         Debug.Log (hit.collider.gameObject.name);
         if (hit.collider.getComponent<Destroyable>() != null)
         {
              hit.collider.getComponent<Destroyable>().DamageMe()
         }

//Script on the Object to destroy

public class Destroyable: MonoBehaviour 
{
    int Health = 5; //Example
    
         public void DamageMe()
         {
             health--;
             if (health <= 0)
             {
                 Die();
             }
         }
         
         void Die(gameObject go)
         {
            Destroy(go);
         }

}

Third: If you use a pooling system, the command to disable an object and recycle it for reuse depends entirely on the pooling system. Most System however simply disable the gameobject like this.

 void Die(gameObject go)
 {
 go.setActive(false);
 }

}

This formatting is killing me…