- Home /
How to detect mouse click on sprite?
Hi guys! Sorry if my question is very simple, but this confused me and I just want understood how unity works with sprites. I have very simple project:
Project contains GameObject "Board" with controller:
public class BoardController : MonoBehaviour {
public int boardRowCount;
public int boardColumnCount;
public GameObject cellPrefab;
void Start()
{
for (var row = 0; row < this.boardRowCount; row++)
{
for (var column = 0; column < this.boardColumnCount; column++)
{
Instantiate(cellPrefab, new Vector3(row, column, 0), Quaternion.identity);
}
}
}
}
and Prefab Cell with controller:
public class CellControler : MonoBehaviour
{
void Update () {
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Click");
}
}
}
This code build next simple table:
My questions next:
Why when I click on the cell it write in console window "Click" 9 times (depends of cell count).
What best way to detect on which cell was clicked.
Answer by Mehul-Rughani · Apr 07, 2015 at 05:04 AM
1) It Displaying "Click" 9 times Because You have assigned Cellcontroller script to each sprite that are instantiated.so click event will be called for every sprite...
2) Add collider to sprite prefab and assign one script to it with OnMouseDown() method and write code u want on click event
Answer by yashpal · Apr 07, 2015 at 05:16 AM
hello @slake ,
1) Why when I click on the cell it write in console window "Click" 9 times (depends of cell count)?
ans :- Input.GetMouseButtonDown(0) is just detect that mouse button is down (means click any where in screen ). it don't depend on mouse click on particular sprite.
2) What best way to detect on which cell was clicked.
Ans:- you just attached collider to your Prefab Cell(ex. boxCollider2D, but you can attach any collider. ). and just use OnMouseDown to detect touch on that particular cell.
here are 2d game learning videos.
here are scripting learning videos.
if you use unity 4.6 or 5. you can use events to detect touch (for that you want to use canvas). here is the new UI learning videos.
I am highly recommend you to check out those videos.