- Home /
Question by
valdiazdanovic · Apr 01, 2015 at 04:42 PM ·
mouse click
How to different hold and one click left button mouse?
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
// how to code if I press long/hold left button mouse?
// how to code if I one click left button mouse?
}
else
{
// this is when I not press left button mouse
}
}
Comment
Answer by KdRWaylander · Apr 02, 2015 at 07:28 AM
Hi, here you go, it's working (at least the JS, is just translated for the C#, i dind't tested it). You can adjust what you call a "long click" by changing the 0.4 value to whatever you want :)
JS:
private var t0:float;
private var longClick:boolean;
private var shortClick:boolean;
/* INITIALIZATION */
function Start () {
t0 = 0;
longClick = false;
shortClick = false;
}
/* READ AT EACH FRAME */
function Update () {
if (Input.GetMouseButtonDown(0)){
t0 = Time.time ;
}
if (Input.GetMouseButtonUp(0) && (Time.time - t0) > 0.4){
longClick = true;
}else if (Input.GetMouseButtonUp(0) && (Time.time - t0) < 0.4){
shortClick = true;
}
// Don't forget to reset to false shortClick or longClick as soon as you use it
// Unless what it will be still true at the next frame and cause issues
}shortClick = false;
}
C#:
float t0;
bool longClick;
bool shortClick;
/* INITIALIZATION */
void Start () {
t0 = 0f;
longClick = false;
shortClick = false;
}
/* READ AT EACH FRAME */
void Update () {
if (Input.GetMouseButtonDown(0))
t0 = Time.time ;
if (Input.GetMouseButtonUp(0) && (Time.time - t0) > 0.4f){
longClick = true;
}else if (Input.GetMouseButtonUp(0) && (Time.time - t0) < 0.4f){
shortClick = true;
}
// Don't forget to reset to false shortClick or longClick as soon as you use it
// Unless what it will be still true at the next frame and cause issues
}
In the C# version longClick
and shortClick
are both defined as floats, though in the code they are assigned with boolean values.
But other than that the code works, and I thank you for it.
Woops, you're right ! I edited that mistake. Thanks !