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);
}
}