- Home /
Why OnMouseDown stops working?
I have this isometric project Im working on and Im using OnMouseDown to detect the clicks on the players, but after a few clicks it seems the OnMouseDown function stops working and doesn't detect the clicks anymore, any ideas why? posted the video on youtube hope you can see the link below
this is most likely a coding issue. Please solve the nullreference you get at startup and post the relevant code parts.
You probably just forget a condition that stops your mousclicks from triggering the on click functions.
Answer by Alexander_Atanasov · Sep 28, 2021 at 04:35 PM
@Ulfnir I'm not pretty sure will it work but try using if(Input.GetMouseDown(0 or 1)) instead of OnMouseDown() and put it in Update() function
@Waystep I ended up doing a raycast function to check if clicked and put it on update, so far its working, but Im not sure whats going on with the onMouseDown, I re-created the tilemaps checked if there was some other collider in front of the player, maybe its something with cinemachine camera and onMouseDown, but Im guessing here, this is the function I ended up creating
private void checkIfClicked()
{
if (Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hits2d = Physics2D.GetRayIntersection(ray,float.MaxValue, LayerMask.GetMask("Unit"));
// Debug.DrawRay(Input.mousePosition, hit.transform.po);
if (hits2d.collider != null)
{
//Debug.Log("hit " + hits2d.collider.name);
if (isTurn)
{
wasPlayerClicked = true;
if (hasMoved == false)
{
highLighTiles(Color.blue, movementSpeed);
}
}
}
}
}
Answer by Ulfnir · Sep 28, 2021 at 11:09 AM
I've read about the null reference and what I found is a bug if you start the game with some game object selected it gives that, if you unselect the game object the game starts without the null error, but it seems unrelated to the onClick problem, about the on click I dont see how it could be the code, here is the onMouseDown function I have in the attached script, the Debug.log is the 1st line in it so it should trigger no matter what
private void OnMouseDown()
{
Debug.Log("Player was clicked");
if (isTurn)
{
wasPlayerClicked = true;
if(hasMoved == false)
{
highLighTiles(Color.blue, movementSpeed);
}
}
}