Advertisement
Deozaan

CoroutineExtensions.cs

Jan 9th, 2013
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4.  
  5. /* Example of how to use
  6. // from rony in #unity3d on Freenode
  7. // the idea is to reduce the code needed for very simple coroutine cases in c# in Unity3D
  8. // in a monoBehaviour
  9. private int hp = 10;
  10.  
  11. void Start() {
  12.  
  13.     //executes the debug.log() after 2 seconds.
  14.     this.ExecuteLater(() => Debug.Log("coucou! 5s"), 2.0f);
  15.  
  16.     //executes the debug.log() when hp < 5
  17.     this.ExecuteWhen(() => Debug.Log("You lost Life!"), () => hp < 5);
  18.  
  19.     //executes the given instructions after 6 seconds
  20.     this.ExecuteLater(() => { Debug.Log("changing HP"); hp = 4; }, 6.0f);
  21. }
  22. */
  23.  
  24. public static class CoroutineExtensions {
  25.     public delegate bool When();
  26.  
  27.     public static void ExecuteWhen(this MonoBehaviour m, Action action, When condition) {
  28.         m.StartCoroutine(ExecuteWhenCoroutine(action, condition));
  29.     }
  30.  
  31.     public static void ExecuteLater(this MonoBehaviour m, Action action, float seconds) {
  32.         m.StartCoroutine(ExecuteLaterCoroutine(action, seconds));
  33.     }
  34.  
  35.     private static IEnumerator ExecuteWhenCoroutine(Action action, When condition) {
  36.         while (!condition()) {
  37.             yield return null;
  38.         }
  39.  
  40.         action();
  41.     }
  42.  
  43.     private static IEnumerator ExecuteLaterCoroutine(Action action, float seconds) {
  44.         yield return new WaitForSeconds(seconds);
  45.         action();
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement