Unity3D: Input Delay when Holding Down a Button

There are times when you want to have a pause between actions performed while the player is holding down a button.  For example, the player is in the main menu and holds in the down key.  You want each menu item to highlight for a few short moments before continuing on. You can do this using a timer and a boolean, as shown below.  Note that all code is written in C#.


Input Delay: It's not glamorous, but it is expected

Initialization

First, we initialize our variables.  I like to use underscores (_) to denote that a variable is private.

Increment The Timer

Next, we increment the timer every frame while the delay is active.  We will set the delay to active later on, when an action is performed.

Handle The Input

The final step is to actually handle the input.  In Dojo Storm, I do this by capturing all input in the Update() function and then calling a specific function based on the input, in this case HandleDirectionPad(Direction in_direction).  However you decide to do it, add code similar to the following to your logic of performing the actual action.

Release The Input

What we have so far almost works, but if the player wants to quickly scroll through items by tapping the down key, they will not be able to.  The delay will start when they press it down the first time, and they will not be able to activate it again for 0.5 seconds.  To account for this, we set the delay to inactive if the player lets go of the button.


That's it!  Now the player can hold the down key to scroll through the menu items, or tap it quickly to scroll through them faster.  I hope this was helpful, and if you have a better way of doing this please feel free to let me know!