Debouncer.cs 832 B

1234567891011121314151617181920212223242526272829
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. namespace JC.Unity {
  5. //防抖器
  6. public class Debouncer {
  7. private Delegate dg;
  8. private object[] args;
  9. private float delayTime;
  10. private Coroutine coroutine;
  11. public Debouncer(Delegate dg, float delayTime) {
  12. this.dg = dg;
  13. this.delayTime = delayTime;
  14. }
  15. public void Invoke(params object[] args) {
  16. if (coroutine != null) {
  17. CoroutineStarter.Stop(coroutine);
  18. coroutine = null;
  19. }
  20. this.args = args;
  21. CoroutineStarter.Start(Execute());
  22. }
  23. private IEnumerator Execute() {
  24. yield return new WaitForSecondsRealtime(delayTime);
  25. dg?.Method?.Invoke(dg.Target, args);
  26. }
  27. }
  28. }