Last active
July 19, 2025 21:05
-
-
Save mminer/2c53b12bc4824d267d5eddd259e40a22 to your computer and use it in GitHub Desktop.
Unity class for coroutine execution debouncing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using UnityEngine; | |
/// <summary> | |
/// Delays execution of an action until a specified time has passed without it being triggered again. | |
/// Useful to prevent rapid-fire calls to expensive operations. | |
/// https://developer.mozilla.org/en-US/docs/Glossary/Debounce | |
/// </summary> | |
public class Debouncer | |
{ | |
Coroutine coroutine; | |
readonly MonoBehaviour coroutineRunner; | |
readonly float delay; | |
public Debouncer(MonoBehaviour coroutineRunner, float delay) | |
{ | |
this.coroutineRunner = coroutineRunner; | |
this.delay = delay; | |
} | |
public void Debounce(Action action) | |
{ | |
if (coroutine != null) | |
{ | |
coroutineRunner.StopCoroutine(coroutine); | |
} | |
coroutine = coroutineRunner.StartCoroutine(InvokeActionAfterDelay(action)); | |
} | |
IEnumerator InvokeActionAfterDelay(Action action) | |
{ | |
yield return new WaitForSeconds(delay); | |
action.Invoke(); | |
coroutine = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment