- Home /
Check if a particular gameobject was clicked
Hello there! I quite new to unity and I have a problem about clicking a particular gameobject. I tried to find ways how to "add an event listener" to a gameobject since that functionality is available only to UI components. It tried to use RaycastHit2D since i m working on a 2D game and it works, but not in the way I would like. What I meant by that is that whenever I click on an object of a kind there is a response from every gameobject of that kind. To help you understand better what I explained, I would post my code:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);
RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
if (hit.collider != null)
{
Debug.Log("Stand " + hit.collider.gameObject.name + "was clicked");
}
}
}
If I click, let's say, stand 4 I get 51 responses(if I have 51 gameobjects of that kind) with the text "Stand 4 was clicked".
My question is what should I do to get only one response with "Stand 4 was clicked"? Thank you for listening!
need more info, but there is nothing in this code to make it repeat or run for each gameObject, I can only assume that the script is on every game object, you should only have one instance of this script running for it to work as expected.
There is also IPointerClick interface to do exactly what you want:
Your answer
![](https://koobas.hobune.stream/wayback/20220613042225im_/https://answers.unity.com/themes/thub/images/avi.jpg)