SHOW:
|
|
- or go back to the newest paste.
1 | using System; | |
2 | using System.Collections; | |
3 | using UnityEngine; | |
4 | ||
5 | public class AdvancedCoroutines : MonoBehaviour | |
6 | { | |
7 | IEnumerator Start() | |
8 | { | |
9 | var isDone = new IsDoneObject(); | |
10 | StartCoroutine(MyActions.DelayedAction(1, () => print("HUZZAH!"), timeRemaining => print(timeRemaining), isDone)); | |
11 | while (!isDone) yield return null; | |
12 | print("Finished"); | |
13 | ||
14 | print("----"); | |
15 | ||
16 | var StopObject = new IsDoneObject(); | |
17 | StartCoroutine(MyActions.StoppableCoroutine(CountToTen(), StopObject)); | |
18 | yield return new WaitForSeconds(5); | |
19 | StopObject.SetDone(); | |
20 | } | |
21 | ||
22 | IEnumerator CountToTen() | |
23 | { | |
24 | for (int i = 1; i <= 10; i++) | |
25 | { | |
26 | print(i.ToString()); | |
27 | yield return new WaitForSeconds(1); | |
28 | } | |
29 | } | |
30 | } | |
31 | ||
32 | public static class MyActions | |
33 | { | |
34 | public static IEnumerator DelayedAction(float delayTime, Action action, Action<float> timeRemaingUpdate = null, IsDoneObject isDone = null) | |
35 | { | |
36 | while (delayTime > 0) | |
37 | { | |
38 | if (timeRemaingUpdate != null) timeRemaingUpdate(delayTime -= Time.deltaTime); | |
39 | yield return null; | |
40 | } | |
41 | ||
42 | action(); | |
43 | if (isDone != null) isDone.SetDone(); | |
44 | } | |
45 | ||
46 | public static IEnumerator StoppableCoroutine(IEnumerator routine, IsDoneObject isDone) | |
47 | { | |
48 | while (!isDone && routine.MoveNext()) yield return routine.Current; | |
49 | } | |
50 | } | |
51 | ||
52 | public class IsDoneObject | |
53 | { | |
54 | private bool isDone = false; | |
55 | ||
56 | public void SetDone() | |
57 | { | |
58 | isDone = true; | |
59 | } | |
60 | ||
61 | public static implicit operator bool(IsDoneObject x) | |
62 | { | |
63 | return x.isDone; | |
64 | } | |
65 | } |