Search code examples
collision-detectionunity-game-engine

Unity c# destroy spawned prefab with mouse click


I have a script to spawn cats at random positions in the game and when the user clicks on them they should be destroyed. I am having trouble with my script however and was wondering if anyone knew what was wrong with the raycast?

public void CatClick () {
            if (Input.GetMouseButtonDown (0)) {
                Ray = Camera.main.ScreenPointToRay (Input.mousePosition);

                if (Physics.Raycast(Ray, out RaycastHit)) {

                    Destroy(RaycastHit.collider.gameObject);
            }
        }

    }

Solution

  • Another way to do it:

     using UnityEngine;
     using System.Collections;
    
     public class CatDestructor : MonoBehaviour 
     {
    
    
         // Use this for initialization
        void Start () 
        {
    
        }
    
         // Update is called once per frame
         void Update () 
        {
    
        }
    
        void OnMouseDown()
        {
            // Destroy game object
            Destroy (this.gameObject);
        }
     }
    

    Put this script on "cat" prefab and if you click on it, it will destroy the "cat".

    Or you must put your code to update function like this:

     void Update(){
       if (Input.GetMouseButtonDown(0)){ // if left button pressed...
         Ray ray = camera.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;
         if (Physics.Raycast(ray, out hit)){
           // the object identified by hit.transform was clicked
           // do whatever you want
         }
       }
     }