Code is running too many times!

Hey everyone. I have a piece of code that executes when I click on an object. The click is based on ray detection so when the script detects the object the ray is colliding with, it runs a certain block of code. Everything works very well, except for the fact that this block of code is in the Update function (I don’t know if I could put it anywhere else) and since it is being run every frame, that block of code might execute multiple times before I manage to release the mouse button. I want it to run only once when I click. For example, I click and release. The code runs once. I click and release again. The code runs once. It should run only once when I release the mouse button.

I thought about using function OnMouseUp() but that only works if the object the code is attached to is clicked on. Not what I want. I’m at a loss about what to do to solve this. Like I said, it runs perfectly as long as the user clicks and releases as fast as they can; but I don’t want that. Thanks for any help. Let me know if this is too confusing.

see Input for something like Input.GetMouseDown()

edit:

Hey Dude,

The simplest solution I could think of at this late hour would be to simply have a flag (boolean variable) control the entry point to your code block.

  1. Enclose your code inside an if statement that checks the flag;
  2. When the mouse is down set the flag to true. Do this before the if statement;
  3. Now inside the block before you exit it set the flag to false;

This will only let you code run once per frame provided the user clicked the mouse in that frame.

There are better (read fancier) ways to do this but this should work just fine.

  • Alex

Thanks for the help! Input.GetMouseButtonUp() was exactly what I needed for this to work. It runs so beautifully now…