Created
June 18, 2019 19:27
-
-
Save unitycoder/c62fb534982830bcab47a3fc7b182f28 to your computer and use it in GitHub Desktop.
Continue CoRoutine After Gameobject was disabled and then enabled (with .setActive)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment