OnMouseDown() is being called twice each time I click on my object. I’ve used a box collider (2D) marked as Trigger and have this code attached to the object:
//toggle red to white on each mousedown to test selection colliders/triggers
void OnMouseDown()
{
Debug.Log("MouseDown Called");
if (isSelected)
{
SetFlagColor(Color.white);
isSelected = false;
}
else
{
SetFlagColor(Color.red);
isSelected = true;
}
}
I am instantiating the object via script (from a Prefab), and I’ve verified through logging that there is definitely only one of the object. There are also no other colliders or calls to OnMouseDown() in any other scripts.
Any ideas? Do I need to manually read the events and consume them?
I think the OnMouseDown function is called very oftenly whenever you click on your mouse button so if keep pressing your mouse button it will keep calling the function. Even if you just click once maybe the script gets several clicks because you pressed it long enough for him to call the function several times.
Try to use the function OnMouseUp. It is called when you stop pressing your mouse button so no matter how long you press your mouse button it will only get one click event. I had the same problem and solved it like that.
I would recommend having one script managing input.
using System;
using UnityEngine;
public class InputController : Monobehaviour
{
public event Action MouseDowned;
public void OnMouseDown()
{
if(MouseDowned!=null)
MouseDowned();
}
}
Then in your script listen to it in the awake function. something like
I have the same problem as @nordee but the func OnMouseUp() did not fix it, moreover the answer from @Rufolangus seems not to work to because i tried it ( i add " var InputManager = new InputController();" before your “InputManager.MouseDowned += MouseDown;” cause i had this: error CS0120: An object reference is required for the non-static field, method, or property ‘InputController.MouseDowned’) and it still fires OnMouseDown or OnMouseUp twice.