- Home /
Mouse click is detected twice
I'm trying to detect two different mouse click but only a single mouse click is detected twice, I don't know whats wrong with the code but I can't detect two separate mouse clicks
bool click = true;
void Update()
{
if(click)
{
if(Input.GetMouseButton(0))
{
print ("Click1");
click = false;
}
}
else
{
if(Input.GetMouseButton(0))
{
print ("Click2");
}
}
}
On single mouse click, I got "Click2", it should be giving "Click1", can anyone explain why I'm getting "Click2" on first mouse click
Edit: copy paste, "update()" function mistake corrected to "Update()"
Answer by robertbu · Aug 29, 2013 at 12:15 PM
'update()' with a lower case 'u' will not work. As for your issue, Input.GetMouseButton(), returns true for every frame the button is held down. It can easily return true for multiple frames. You want to use Input.GetMouseButtonDown() or InputGetMouseButtonUp(). Here is a bit of a rewrite to your logic:
using UnityEngine;
using System.Collections;
public class Bug27 : MonoBehaviour {
bool click = true;
void Update()
{
if(click)
{
if(Input.GetMouseButtonDown(0))
{
Debug.Log ("Click1");
click = false;
}
}
else
{
if(Input.GetMouseButtonDown(0))
{
Debug.Log ("Click2");
click = true;
}
}
}
}
Sorry, it was a copy paste mistake .. $$anonymous$$y code has Update with Capital "U", and still output is same
Did you test the code I pasted above using Get$$anonymous$$ouseButtonDown()? I tested it before I pasted it, and it worked fine. Note your original code was missing the 'click = true;' on line 21.
Did you change the click variable from public to private later on? That once was the problem for me as Unity seems to keep the previously inspector set value in cache until scene reload or variable rena$$anonymous$$g.
On your original code, you are getting 'Click2' because your are using Get$$anonymous$$ouseButton(). Get$$anonymous$$ouseButton() returns true for every frame the mouse buttons is held down. A typical mouse click will last for several frames. If you replace your 'Input.Get$$anonymous$$ouseButton()' calls with 'Input.Get$$anonymous$$ouseButtonDown()' calls, you will get 'Click1' the first time the button is pressed. After that, you will get 'Click2' for all other mouse clicks.
Your answer
![](https://koobas.hobune.stream/wayback/20220613113213im_/https://answers.unity.com/themes/thub/images/avi.jpg)