Problem with nested Start Coroutine in loop
Hi, this question probably has a simple solution but I cant seem to find it in the Unity documentation or in past problems. Im trying to get a platform to move up 30 spaces along y axis wait 5 seconds, move down 30 spaces along y axis and then repeat this for the duration of the game. For some reason the platform either moves only up, only down or moves up once and then stops. Any help would be greatly appreciated. The code I use has been attached.
please paste your actual code not screenshots of it. sometimes it's necessary to use the code in order to help you, and it's unlikely that anyone will type in in... the user guide/faq (linked from the right rail) explain how to...
using UnityEngine;
using System.Collections;
public class LiftController : $$anonymous$$onoBehaviour {
void Start () {
// for (int i = 0; i > 10; i ++) {
// StartCoroutine (Wait ());
//}
}
void Awake(){
StartCoroutine ("Wait");
}
void Update () {
//StartCoroutine (Wait ());
}
IEnumerator Wait(){
while (true) {
yield return new WaitForSeconds(5);
transform.Translate (new Vector3(0, 30, 0));
StartCoroutine (Wait2 ());
}
}
IEnumerator Wait2(){
yield return new WaitForSeconds (5);
transform.Translate (new Vector3(0, -30, 0));
}
}
Answer by pekalicious · Dec 04, 2015 at 06:51 PM
You are calling Wait2 without yielding, which means that it will start the coroutine but not wait for it to complete, so it will immediately go to the first WaitForSeconds. And because both coroutines wait 5 seconds, they will execute the transform logic at the same time, resulting in unpredictable behavior.
Change
StartCoroutine (Wait2 ());
To
yield return StartCoroutine (Wait2 ());
Ok thanks pekalicious, that solved it. Unfortunately I lost most of the game with the new update but my scripts were still saved, so i'll keep them for future reference. :)
Your answer
Follow this Question
Related Questions
Why isn't my coroutine working when I call it from another script. 0 Answers
How do i make Unity seamlessly loop my background music? 5 Answers
Video not playing completely? 0 Answers
For loop work well except on third state 1 Answer
Trigger a certain number of loop in animation on button down 0 Answers