Hi. I’m trying to click on a sprite and destroy it, but I’m having problems. First, my code isn’t even detecting when I click on a collider and second, even if I did detect a collision of any sort, I don’t know how to specify which object I want to destroy. What am I doing wrong? Thanks.
function Update () {
if (Input.GetMouseButtonDown (0)) {
var pos : Vector2 = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
var hit: RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(pos), Vector2.zero);
if (hit.collider != null) {
Debug.Log("Hit");
// Destroy(HitObject);
}
}
}
Destroy(hit.collider.gameObject)
For the detection:
-
add the 2d physic rayscater component to your camera
-
add the EventTrigger component to your gameobject
-
add the event you want (I think it OnPointerClick or OnPointerDown)
-
Drag and drop the gameobject you want to destroy
-
call your method to destroy the object
Cheers