Search code examples
unity-game-engineonclickgameobject

how to prevent others than the top most gameobject receive clicked event in a stacked gameobjects


I have an object with a BoxCollider2D, which is lying under an object with a BoxCollider. (Details is an UI (I use NGUI asset) with a BoxCollider lying on top of a GameObject with a BoxCollider2D). The UI object has a script which implements OnClick() and the GameObject has a script implementing OnMouseDown(). When I click the UI object, click events fire from the GameObject as well.

I just want the UI object fire event when they are stacking on each other. How can I achieve this ?


Solution

  • Include using UnityEngine.EventSystems; In your OnMouseDown() function, add if (!EventSystem.current.IsPointerOverGameObject()) then put all the code that is suppose to run when mouse is down inside the if statement.

    using UnityEngine.EventSystems;
    public void OnMouseDown()
    {
     if (!EventSystem.current.IsPointerOverGameObject())
     {
      //Put all your code for your gameobject here
     }
    }
    

    That should work but if it doesn't, Watch this video for other ways to do this.