I am trying to delete the object on which the mouse is clicked. I am making a 2D game using the new Unity3D 4.3. Here is the code I\'m using
void Update () {
First attach any type of 2D collider to your GameObject, then pick one of those solutions;
1st Case - If there are more than 1 GameObject on top of each other, and you try to understand specific GameObject is clicked:
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit2D[] hits = Physics2D.GetRayIntersectionAll (ray, Mathf.Infinity);
foreach (var hit in hits) {
if (hit.collider.name == name) {
MyFunction ();
}
}
}
}
2nd Case - If there is only 1 GameObject, and you try to understand if it is clicked:
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit2D hit = Physics2D.GetRayIntersection (ray, Mathf.Infinity);
if (hit.collider != null && hit.collider.name == name) {
MyFunction ();
}
}
}