Delegate Activation Timer (Example)


/ Published in: C#
Save to your folder(s)

A timer that activates a delegate after a set amount of time. Coded for Unity. This example shows the implementation of an event where all subscribed methods are activated every second. For methods with more elaborate signatures, new delegates will have to be added.

The public IEnumerator can be started from external classes using "StartCoroutine()" and can be passed methods from that class matching the TimerCallbacks delegate signature.


Copy this code and paste it in your HTML
  1. public delegate void TimerCallbacks();
  2. public static event TimerCallbacks EverySecond;
  3.  
  4. void Start ()
  5. {
  6. StartCoroutine(Timer(1f, EverySecond, true));
  7. }
  8.  
  9. public IEnumerator Timer (float timeDelay, TimerCallbacks methodToCall, bool loop = false)
  10. {
  11. if (loop)
  12. {
  13. yield return new WaitForSeconds (timeDelay);
  14.  
  15. if (methodToCall != null)
  16. {
  17. methodToCall ();
  18. }
  19.  
  20. yield return StartCoroutine (Timer(timeDelay, methodToCall, true));
  21. }
  22. else
  23. {
  24. yield return new WaitForSeconds (timeDelay);
  25.  
  26. if (methodToCall != null)
  27. {
  28. methodToCall ();
  29. }
  30.  
  31. yield return null;
  32. }
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.