- Home /
How to detect mouse click on new Unity 4.3 Sprite
I've added a Unity 4.3 Sprite to my scene. I can start it animating with a keypress. But I can't figure out how to detect mouse clicks or finger taps on the sprite.
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 ins$$anonymous$$d.
Answer by komodor · Dec 05, 2013 at 01:50 AM
sprite is gameObject as any others so
http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnMouseDown.html http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnMouseUp.html
should work
edit: the game object needs to have Collider
Answer by Linus · Feb 10, 2014 at 09:04 PM
Here is another example.
-Sprite needs to have a 2d collider
-have this script on a game object in scene
-make sure camera is orthographic, they are not when making a new scene even in 2d mode
-if to be used as is, place a prefab into the slot that appears in the inspector
#pragma strict
var tileSelectionMarker : GameObject;
private var selectorSprite : GameObject;
function Start () {
selectorSprite = Instantiate (tileSelectionMarker, Vector3(0,0, 0), Quaternion.identity);
}
function Update () {
if(Input.GetMouseButtonDown(0)){
var mousePosition : Vector2 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var hitCollider : Collider2D = Physics2D.OverlapPoint(mousePosition);
Debug.Log("mouse pos "+mousePosition.x+" y "+mousePosition.y+" ");
if(hitCollider){
selectorSprite.transform.position.x = hitCollider.transform.position.x;
selectorSprite.transform.position.y = hitCollider.transform.position.y;
Debug.Log("Hit "+hitCollider.transform.name+" x"+hitCollider.transform.position.x+" y "+hitCollider.transform.position.y);
}
}
}
Answer by Romano · Feb 03, 2014 at 12:45 PM
I wrote a script that does clicks and takes the new sorting layers and sorting order into account, check it out with some long explanation here: http://notquiteblackandwhite.com/post/75474540217/how-to-do-2d-mouse-clicks-in-unity
Direct link to the script http://pastebin.com/Vbzrt0z7 Worth to checkout if you have multiple sprites and need to only click the closest one.
http://pastebin.com/y8iVHZGr -- updated for my needs, thanks for the good starting point, figured I'd pay it back by sharing my code as well :)
Answer by siddharth3322 · May 14, 2014 at 05:14 AM
you have to attach any type of collider to you gameobject.
Other all required detail you can find in my following post.
http://answers.unity3d.com/questions/619090/touch-detection-in-2d-game.html
If you want any other detail then feel free to ask.