-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelayOneFrame.cs
More file actions
93 lines (77 loc) · 2.88 KB
/
DelayOneFrame.cs
File metadata and controls
93 lines (77 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
namespace KongZEE.Timer.Delay
{
public class DelayOneFrame
{
private MonoBehaviour monoBehaviour;
Dictionary<OneFrameKey, Coroutine> coroutines = new ();
private OneFrameKey delayKeyDisposable;
public DelayOneFrame(MonoBehaviour monoBehaviour)
{
this.monoBehaviour = monoBehaviour;
}
public void StartDelayDisposable(UnityAction<bool> action = null)
{
if (coroutines.Count > 0 && coroutines.ContainsKey(delayKeyDisposable))
{
monoBehaviour.StopCoroutine(coroutines[delayKeyDisposable]);
coroutines.Remove(delayKeyDisposable);
}
delayKeyDisposable = StartDelay(action);
}
public OneFrameKey StartDelay(UnityAction<bool> action = null)
{
OneFrameKey delayKey = new OneFrameKey();
if (action != null)
{
action += isNextFrame => { delayKey.nextFrame = isNextFrame; };
}
Coroutine coroutine = monoBehaviour.StartCoroutine(Timer(action));
coroutines.Add(delayKey, coroutine);
delayKey.action = action;
return delayKey;
}
public void StartDelay(OneFrameKey delayKey = null)
{
if (coroutines.Count < 0) return;
if (delayKey == null)
{
if (coroutines.Count > 0)
{
monoBehaviour.StopCoroutine(coroutines.Values.ElementAt(0));
coroutines.Remove(coroutines.Keys.ElementAt(0));
}
}else if (coroutines.ContainsKey(delayKey))
{
monoBehaviour.StopCoroutine(coroutines[delayKey]);
coroutines.Remove(delayKey);
}
OneFrameKey currentDelayKey = delayKey ?? coroutines.Keys.ElementAt(0);
currentDelayKey.nextFrame = false;
Coroutine coroutine = monoBehaviour.StartCoroutine(Timer(currentDelayKey.action));
coroutines.Add(currentDelayKey, coroutine);
}
private IEnumerator Timer(UnityAction<bool> action)
{
Debug.Log($"Old Time: {Time.deltaTime}");
action?.Invoke(false);
yield return null;
action?.Invoke(true);
Debug.Log($"New Time: {Time.deltaTime}");
}
}
[Serializable]
public class OneFrameKey
{
public bool nextFrame;
public UnityAction<bool> action;
public OneFrameKey()
{
}
}
}