Search Unity

OnMouseDown, Multiple Sprites, Get Sprite On Top

Discussion in 'Scripting' started by wabugi, Jan 11, 2015.

  1. wabugi

    wabugi

    Joined:
    Nov 4, 2014
    Posts:
    17
    Hello everyone!

    I'm currently working on a 2D game where multiple game objects are stacked on top of each other. Each game object has a sprite renderer, a collider2d and a script attached. In the script, I use the methods OnMouseDown, OnMouseDrag and OnMouseUp to achieve a drag and drop functionality.

    The problem is, when there are multiple sprites stacked, the OnMouseDown method seems to choose a random game object instead of choosing the one that is visible on top. It does completely ignore variables like sprite layer sorting order.

    I found a solution using google and the unity site. Instead of using the OnMouseX methods on every game object, I created another game object with a "controller" script attached. This script uses various methods, inlcuding raycasts, to find the game object on top (via tag and sprite sorting order). The script then uses custom methods to move the target game object. So far so good.

    Does anybody know if the Unity team does plan to give some more functionality to the OnMouseDown method in the near future? Maybe in Unity 5? If not, is my solution the best thing I can do?
     
  2. Dameon_

    Dameon_

    Joined:
    Apr 11, 2014
    Posts:
    542
    There's already better functionality in 4.6 that covers what you want from the dev team. Check out 4.6's Event System.

    Your problem, as far as I understand, is that you have a bunch of overlapping colliders. It's not the visible sprite that gets hit by a raycast, it's the collider. If a bunch of colliders are right on top of each other, the engine has no way of knowing which you want.
     
    wabugi likes this.
  3. wabugi

    wabugi

    Joined:
    Nov 4, 2014
    Posts:
    17
    It seems like my reply yesterday has not been saved. Alright, once again ;)

    The new Event System looks promising. I will have a look at it today. Thank you!