- Home /
Delay my Scene for few seconds, not sure what wrong
using UnityEngine; using System.Collections;
public class GameManager : MonoBehaviour { public GameObject asteroidsGenerator; public GUIText guiTextScore; public int timeInterval = 1; public float delayTime = 2f; float time; int totalTime; void Start () { Instantiate(asteroidsGenerator, Vector3.zero, Quaternion.identity); time = 0f; totalTime = 0; } void Update () { time += Time.deltaTime; if(AsteroidsGenerator.isActive) { if(time >= timeInterval) { totalTime += timeInterval; guiTextScore.text = "X " + totalTime.ToString(); time = 0f; } } else GameOver(); } IEnumerator GameOver() { guiTextScore.text = "Your Total Score Is:" + totalTime.ToString(); yield return StartCoroutine(MyDelayMethod(delayTime)); Application.LoadLevel(2); } IEnumerator MyDelayMethod(float delay) { yield return new WaitForSeconds(delay); } }
Well this my code, not sure what im doing wrong, is there any other way to implement the delay?
Answer by FakeBerenger · Nov 07, 2012 at 11:16 PM
You need to call GameOver with StartCoroutine, just like MyDelayMethod, or the yield won't do anything.
And, please, format your code.
Answer by aldonaletto · Nov 08, 2012 at 12:04 AM
You should not call GameOver directly, as @FakeBerenger said: use StartCoroutine(GameOver) instead. But there's another problem: if you use StartCoroutine inside Update, a new GameOver coroutine will be started each frame, crowding the memory with GameOver instances running in parallel.
In order to avoid this, use a simple boolean flag to ensure that GameOver is started only once:
...
int totalTime;
bool gameOver = false; // boolean flag
...
void Update ()
{
time += Time.deltaTime;
if(AsteroidsGenerator.isActive)
{
...
}
else
if (!gameOver){ // only start GameOver once
StartCoroutine(GameOver());
gameOver = true; // no more GameOver calls
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613083515im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to translate code with yield waitforseconds to c#? 1 Answer
WaitForSeconds Question 2 Answers
Delay in a IEnumerator 2 Answers
Delay when reloading 0 Answers
Delay in Instantiate only runs once 2 Answers