Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active July 19, 2025 21:05
Show Gist options
  • Save mminer/2c53b12bc4824d267d5eddd259e40a22 to your computer and use it in GitHub Desktop.
Save mminer/2c53b12bc4824d267d5eddd259e40a22 to your computer and use it in GitHub Desktop.
Unity class for coroutine execution debouncing.
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