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.
7 Answers
7sprite is gameObject as any others so
should work
edit:
the game object needs to have Collider
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);
}
}
}
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: Not Quite Black and White
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.
– Linushttp://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 :)
– shopguyyou have to attach any type of collider to you gameobject.
Other all required detail you can find in my following post.
If you want any other detail then feel free to ask.
try this,
function OnMouseOver () {
if(Input.GetMouseButtonDown(0)){
//your code
}
}
Just write this code and add it to the main camera the console will show the results
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);
if (hit.collider.name == "Tied_Seed") {
Debug.Log (hit.collider.name);
}
}
}
The only way for this to work, apart from making sure there is
– rosdiCollidercomponent, is to make sure theZindex of the object is on top, even if you are making 2D games. The sorting layer is ignored and Z index take precedence instead.