- Home /
Click or touch getting detected multiple times
Hello everyone, i think this question might have already been asked multiple times having checked the forum but I wasn't able to fix the problem. I'm trying to increment an integer variable based on if the player clicks or touches an object. The problem is every time I click, it updates the variable twice instead of once. This however works fine if use the OnMouseDown function rather than the Update function. Here's my code:
void Update()
{
if (transform.position.y < -5.0f)
{
Debug.Log("Destroying Object!");
Destroy(gameObject);
}
#if UNITY_EDITOR
if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log("Hit the Block!");
//Spawn the splash object
Instantiate(BlockSplashObject, hit.transform.position, Quaternion.identity);
//destroy the object finally
Destroy(gameObject);
player.GetComponent<PlayerState>().UpdateScore();
}
}
#endif
}
Even while debugging, the breakpoint hit twice at the call of the UpdateScore function. How would I go about solving this issue, whether I need to use a boolean or tracking a time stamp? I would really appreciate your help.
Answer by corpsinheretoo · Oct 02, 2018 at 02:02 AM
I think GetMouseButton(0) returns true repeated as long as you hold down mouse1; while GetMouseButtonDown(0) will only return true during the one frame the mouse is first pressed - then resets once you release the mousebutton. Try removing GetMouseButton(0).
That seems to work if I apply the script to a static object. Thanks! Is it a similar thing for touch input since I used this: if (Input.GetTouch(0).phase == TouchPhase.Began) // do the same thing as above" and it updated twice.