I am learning Unity from a book. The example is to create a 2D memory game as follows (viewed in perspective view).

enter image description here

The green (background) at z=5, the purple diamond (front card) at z=0 and the red (back card) at z=-5 for example. The front card is set as the parent of the back card in the hierarchy window.

A box collider (2D) component and a script below are attached only to the parent.

public class FrontCard: MonoBehaviour
    public void OnMouseDown()
        Debug.Log("testing 1, 2, 3!");

When I play the game and click the back card, the OnMouseDown gets invoked.


How can the OnMouseDown get invoked when I click the back card by considering the script is attached to the front card game object that is placed below the back card?

  • \$\begingroup\$ Does the back card, that is placed as a child of the front card, inherit the OnMouseDown? \$\endgroup\$ – Money Oriented Programmer Jul 13 at 10:09
  • 1
    \$\begingroup\$ Does the card back have its own collider to block the mouse's raycast? \$\endgroup\$ – DMGregory Jul 13 at 11:16
  • \$\begingroup\$ @DMGregory: The back card is the child of the front card. The back card has only : Transform, Sprite Renderer components. \$\endgroup\$ – Money Oriented Programmer Jul 13 at 11:23

As always, your very first step should be to read the documentation for the methods you're using:

OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.

Under the hood, having an OnMouseDown function tells Unity to fire a ray from the main camera each frame, through the on-screen position of the mouse/stylus/touches. Rays detect colliders.

If your back card has no collider, it's completely invisible to the raycast, and they ray will go straight through it to hit the front card's collider.

  • \$\begingroup\$ If I read the linked documentation, I would not be able to understand because the documentation does not mention what you said in this answer. :-) \$\endgroup\$ – Money Oriented Programmer Jul 13 at 11:31
  • 1
    \$\begingroup\$ I bolded the spot where it describes that OnMouseDown is called based on colliders. Don't underestimate your ability to glean useful information from thoroughly reading the docs. \$\endgroup\$ – DMGregory Jul 13 at 11:33
  • 1
    \$\begingroup\$ @DMGregory but if people start to read documentation then this Q&A will lose more than 50% of the visitors. \$\endgroup\$ – Ocelot Jul 13 at 22:02
  • \$\begingroup\$ @Ocelot: In addition, reading the manual makes the learning run slower. \$\endgroup\$ – Money Oriented Programmer Jul 14 at 17:51

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.