- Home /
Detecting Mouse Click on 2D Sprite
Hello, all I'm trying to do is detect if the sprite rectangle contains the mouse position however I have no idea how to get access to a Sprite gameObject's rectangle. I have the same effect working with GUIText but would like to make this work to make a menu using sprites as buttons.
I'd appreciate any help, thank you.
Answer by Eric5h5 · Nov 13, 2013 at 08:29 PM
The OnMouseDown/Over/Up functions work as usual. Like all objects except GUIElements, sprites need colliders for that to work.
Ah, thanks very much. I'm somewhat new to Unity and am still trying to understand all the basics.
Answer by rosdi · Jun 01, 2014 at 09:10 AM
The only way for this to work, apart from making sure there is Collider
component, is to make sure the Z
index of the object is on top, even if you are making 2D games. The sorting layer is ignored and Z index take precedence instead.
So this means you may not be able to attach your sprite under another game object. I tried parenting my sprite under another game object and my mouse click is no longer detected.
Rosdi, Im having this same problem, I tried removing the parent object but no luck... I didnt quite get the "Z index" you said, you mean that is must be the closest object to the camara in Z axis? like not having any object in between consu$$anonymous$$g the mouse events?
Cheers and thanks for your help!
@nsxNawe, Yes.. to test this create a simple project with two sprites in the scene.. one sprite make its Z
index 0
and another -1
. Both game object must have Collider 2D
component. Only the object with -1
Z
index will capture the On$$anonymous$$ouseUp
event.
$$anonymous$$any thanks @rosdi ! You made my day great !!! 2D mouse Click working after changing z values
Answer by pctroll · Nov 13, 2013 at 09:48 PM
Add a collider to the game object (preferably 2D) and then call the functions OnMouseDown/Over/Up as @Eric5h5 told you. I want to emphasize that these functions won't work unless you add a collider component.
It does not have to be a trigger, it just needs a collider component attached. Hope that helps
Answer by Romano · Feb 03, 2014 at 12:23 PM
I've just put a post on my game's blog about 2D mouse clicking in unity because I had such a hard time finding the answer anywhere. There's also a link to a javascript script that allows you to click on sprites taking into account their sorting layer and sorting order. Hope this helps: http://notquiteblackandwhite.com/post/75474540217/how-to-do-2d-mouse-clicks-in-unity
Your answer
Follow this Question
Related Questions
Using RayCast to Get Mouse Input 1 Answer
Help paint will not work!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 2 Answers
Run script when object is clicked 1 Answer
Auto Primitive Collider 3 Answers
Camera Orbit on Left Click problem 0 Answers