-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContinueCoroutine.cs
More file actions
54 lines (43 loc) · 1.27 KB
/
ContinueCoroutine.cs
File metadata and controls
54 lines (43 loc) · 1.27 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
// example script for restarting Coroutine after gameobject was disabled (and continue from previous timer value)
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ContinueCoroutine : MonoBehaviour
{
public float duration = 5f;
Image image;
bool isRunning = true;
float timer = 0;
float oldtimer = 0;
private void Awake()
{
image = GetComponent<Image>();
}
// keep timer values on disable
private void OnDisable()
{
oldtimer = timer;
isRunning = false;
}
// start coroutine on enable
private void OnEnable()
{
timer = oldtimer;
isRunning = true;
StartCoroutine(CustomUpdater());
}
// coroutine loop
IEnumerator CustomUpdater()
{
while (true)
{
for (timer = oldtimer; timer < duration; timer += Time.deltaTime) // this works, since we keep reference to old timer
// for (float timer = 0; timer < duration; timer += Time.deltaTime) // this doesnt work, because restarting coroutine would reset timer value
{
image.color = Color.Lerp(Color.red, Color.green, timer / duration);
yield return 0;
}
oldtimer = 0;
}
}
}