jason
jason

Reputation: 1172

What is the proper way to handle mouse clicks in unity?

I am checking if Input.GetMouseButtonDown(0) then printing to Debug.log but because the update() function runs every frame the output happens many times. What is the best way to handle this so it doesn't run multiple times immediately?

Upvotes: 2

Views: 2157

Answers (2)

Ron
Ron

Reputation: 1866

Input.GetMouseButtonDown(0) returns true only on the frame that the user actually clicked the mouse (or finger) down; if you are seeing your log running multiple times, it's because you have your script on multiple objects running at the same time.

From Unity's documentation:

Returns true during the frame the user pressed the given mouse button.

You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the mouse button and pressed it again. button values are 0 for the primary button (often the left button), 1 for secondary button, and 2 for the middle button.

Upvotes: 2

Related Questions