Search code examples
c#unity-game-engineinstantiationdestroy

Destroy Clone On Click


I currently been trying for 2 days now to destroy an instantiated prefab clone with a mouse click.

The code below does 2 things auto destroys them after a set interval which works great. The click function destroys all the clones even if i click on the prefab or not which isn't what I'm wanting it to do.

Update: This project is in 2d

I'm have searched on here and have asked others on different scripting platforms and their advice doesn't seem to help.

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

 public class DestroyOnClick : MonoBehaviour
 {
     public float lifeTime = 10f;


     void Update()
     {
         if (Input.GetMouseButton(0))
         {
             Destruction();
         }

         if (lifeTime > 0)
         {
             lifeTime -= Time.deltaTime;
             if(lifeTime <= 0)
             {
                 Destruction();
             }
         }


     }


     void Destruction()
     {
         Destroy(this.gameObject);
     }
 }

Solution

  • Have your Monobehaviour implement the PointerClick or PointerDown Event handler, and make sure you have an EventSystem in your scene, and a raycaster on the active camera.

    //something along these lines:
    using UnityEngine;
    public class DestroyOnClick : Monobehaviour, IPointerClickHandler
    {
        public void OnPointerClick(PointerClickEventData data)
        {
            Destroy(this.gameObject);
        }
    }