Replies: 1 comment
-
This is my approach using Cysharp.Threading.Tasks;
using System;
using System.Threading;
public class Debouncer
{
private readonly float debounceTime;
private readonly Action action;
private CancellationTokenSource cts;
public Debouncer(float ms, Action action)
{
this.debounceTime = ms;
this.action = action;
}
public void Call()
{
cts?.Cancel();
cts = new CancellationTokenSource();
DebounceCall(cts.Token).Forget();
}
private async UniTask DebounceCall(CancellationToken cancellationToken)
{
await UniTask.Delay(TimeSpan.FromMilliseconds(debounceTime), cancellationToken: cancellationToken);
if (!cancellationToken.IsCancellationRequested)
{
action();
}
}
} And how to use it using UnityEngine;
public class UniTaskDebounceExample : MonoBehaviour
{
private Debouncer debouncer;
private void Start()
{
debouncer = new Debouncer(500, () => Debug.Log("Hello world!"));
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
debouncer.Call();
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi there,
I'm having hard time implemeting debounce method using UniTask
https://angular.io/guide/http-optimize-server-interaction
I'd appreciate if someone provides the right approach.
Please advise
My failed attempt
Beta Was this translation helpful? Give feedback.
All reactions