0
\$\begingroup\$

I have two sprites. One for the entire background and another small sprite, which is a foreground object. I have written code for both of these objects in their OnMouseDown() functions. When I click on the foreground object, theMouseDown()method of background object also gets called since it is behind the foreground.I just want my foreground sprite to react when I click it, not both foreground and background sprites.

\$\endgroup\$
1
\$\begingroup\$

OnMouseDown() should normally work, make sure that both the sprites have separate scripts attached to them, with OnMouseDown() defined in each script. A collider should be attached to the script for the mouse click to work, in any case.

You can do debugging like this:

void OnMouseDown()
{
   Debug.Log(sprite.name);
}

Or still if things dont work, then try this piece of code instead

if (Input.GetMouseButtonDown(0))
{
    RaycastHit hit;
    if (Physics2D.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
    {
        if (hit.collider == collider)
        {
            //Do your thing.
        }
    }
}

Hope this helps.

\$\endgroup\$
  • \$\begingroup\$ Yeah I already tried the first solution with Debug.Log(). It prints the name of the background. \$\endgroup\$ – Anish Sharma Oct 20 '16 at 9:23
  • \$\begingroup\$ If it prints the name of the background even when you click on your other object, please see if both the sprites are having different sorting layers. See if the z value of transform of both the sprites are different. You can visually see this by changing the 2D scene to 3D view. \$\endgroup\$ – Geo Baby Oct 20 '16 at 9:28
1
\$\begingroup\$

You need to use RaycastAll and not Raycast, as suggested by others.

if (Input.GetMouseButtonDown(0))
{
    Vector2 mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    RaycastHit2D[] hits = Physics2D.RaycastAll (mousePosition, new Vector2 (0, 0), 0.01f);
}

I would also suggest you tag your gameobject, and then use the tag to check if the object is the type you are looking for:

for (int i = 0; i < hits.Length; i++) {
     if (hits [i].collider.tag == "Foreground")     
         //collider.GetComponent<ForegroundScript>().DoSomething();
}
\$\endgroup\$
0
\$\begingroup\$

The solution for this is to add raycaster to your sprites.

See this stackoverflow question for details :

https://stackoverflow.com/questions/35529940/how-to-make-gameplay-ignore-clicks-on-ui-button-in-unity3d

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.