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 () {
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit))
{
isHit = false;
Destroy(GameObject.Find(hit.collider.gameObject.name));
}
}
}
The control is not entering the inner if loop. (isHit
is not being set as false).
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 ();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With