raycast mouse detects any object

Hi, i want to detect a mouse click on a especific object using raycast, but for some reason my code detects all the objects that have a collision when you click on them, here is my code.

        if(Input.GetMouseButtonDown(0))
        {
            Vector2 MousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D Hit = Physics2D.Raycast(MousePos,Vector2.zero);
            if(Hit)
            {
                gameObject.GetComponent<Animator>().SetBool("Push", true);
                MouseDown = true;
            }
        }

Thank you.

Hi @Fivii

You just need to find a way to ask what object was hit. There plenty of ways to do this, for example by checking if the object hit has a certain tag, or by playing around with physics layers, or even by just checking the name of the object that was hit. Taking that last solution and applying it to your code should be simple enough:

        if (Input.GetMouseButtonDown(0)) 
        {
            Vector2 MousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D Hit = Physics2D.Raycast(MousePos, Vector2.zero);
            if (Hit && Hit.collider.name == "NameOfYourGameobject")
            {
                gameObject.GetComponent<Animator>().SetBool("Push", true);
                MouseDown = true;
            }
        }