Reputation: 389
How to make button press function work only in between # seconds? For example, allow user to press E at any time, but execute, for example, animation every 5 seconds? I've tried Invoke but it doesnt seem to work as it should. I've also tried timestamp and StartCoroutine (waitforseconds).
Here's what I got so you can see:
void Update()
{
if (triggerIsOn && Input.GetKeyDown(KeyCode.E))
{
drinkAmin.Play("DrinkVodka");
StartCoroutine(letsWait());
}
}
And
IEnumerator letsWait(){
Debug.Log ("lets wait works!");
yield return new WaitForSeconds (5);
TakeAshot ();
}
It all works, but not by 5 seconds in between, but rather it works every 5 seconds after each button press. So, this doesn't work as it should. Can anyone help me? A bit lost here. Thanks!
Upvotes: 3
Views: 3158
Reputation: 331
I came up with a solution for debouncing input events in Unity by using coroutines and unique identifiers for each coroutine call.
public class Behaviour : MonoBehaviour
{
private Guid Latest;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
// start the debounced input handler coroutine here
StartCoroutine(Debounced());
}
}
private IEnumerator Debounced()
{
// generate a new id and set it as the latest one
var guid = Guid.NewGuid();
Latest = guide;
// set the denounce duration here
yield return new WaitForSeconds(3);
// check if this call is still the latest one
if (Latest == guid)
{
// place your debounced input handler code here
}
}
}
What this code does is generates a unique id for each call of the Debounced
method and sets the id of the latest Debounced
call. If the latest call id matches the current call id then the code is executed. Otherwise, another call happened before this one so we don't run the code for that one.
The Guid
class is in the System
namespace so you will need to add a using statement at the top of the file: using System;
.
Upvotes: 2
Reputation: 1535
What you're talking about is called a 'debouncer'. There's a good SO question about this already: C# event debounce - try using one of the approaches there.
Upvotes: 1