Question by
lilshredder · Nov 09, 2017 at 09:11 PM ·
errorcoroutinedelayhow
Wait for 7 Seconds not working
I am having problems with the StartCoroutine to wait for 5 seconds. I directly used the example from unity, but it is not working. Help is greatly appreciated. Thank you!
using UnityEngine; using System.Collections;
public class ToScene2 : MonoBehaviour {
public GameObject[] Scene1;
public GameObject[] Scene2;
public GameObject[] Scene2Loaded;
IEnumerator Example()
{
print(Time.time);
yield return new WaitForSeconds(5);
print(Time.time);
}
// Update is called once per frame
void Start () {
Vector3 pos = new Vector3 (0, 0, 0);
transform.position = pos;
StartCoroutine(Example());
{
for (int i = 0; i < Scene1.Length; i++) {
Destroy (Scene1 [i].gameObject);
}
for (int i = 0; i < Scene2.Length; i++) {
Instantiate (Scene2 [i], transform.position, Quaternion.identity);
}
}
}
}
Comment
Answer by Dryn27 · Nov 09, 2017 at 10:39 PM
It's working, but not as you think. That coroutine is waiting 5 seconds, but that doesn't stop the Start function from going on with its code, only stops the code inside the coroutine. You can write the code inside that coroutine instead, to have it the way you want, something like:
public class ToScene2 : MonoBehaviour {
public GameObject[] Scene1;
public GameObject[] Scene2;
public GameObject[] Scene2Loaded;
IEnumerator Example()
{
print(Time.time);
yield return new WaitForSeconds(5);
print(Time.time);
for (int i = 0; i < Scene1.Length; i++) {
Destroy (Scene1 [i].gameObject);
}
for (int i = 0; i < Scene2.Length; i++) {
Instantiate (Scene2 [i], transform.position, Quaternion.identity);
}
}
// Update is called once per frame
void Start () {
Vector3 pos = new Vector3 (0, 0, 0);
transform.position = pos;
StartCoroutine(Example());
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612142628im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do i fix this error? 0 Answers
Parsing error CS8205,Parsing Error CS8205 2 Answers
Setting button intractability causes an error 1 Answer
C# Simple delay at void Update? 2 Answers