- Home /
Coroutine loop not working
Hi everyone,
I'm currently stuck on a Coroutine loop that does not seem to work.
I've tried simplifying the loop to its essence to see what is wrong, but to no avail. Here's the code:
void Start()
{
StartCoroutine(Timer());
}
IEnumerator Timer()
{
while (true)
{
Debug.Log("Here it works");
yield return new WaitForSeconds(1f);
Debug.Log("So does here");
}
}
Basically, the first Debug.Log shows on the console just the first time, while the second never appears.
I can't seem to find the issue, what am I missing?
Thanks in advance for the help.
Cheers
Are there any other scripts running in the background? or does the GameObject with the coroutine ever get destroyed?
Hi Caeser,
no, the object is always active and there are no other scripts interfering with this Coroutine. Now I've tried to bypass it by starting the coroutine in Update with a boolean that switches on/off, but I don't think it would be a great idea in the long run.
Cheers
Hmmm, just to clarify you aren't setting Time.timeScle = 0
anywhere right... Maybe try using a Timer instead of a Coroutine like :
private float Timer;
private float MaxTime = 1f;
bool HasRunned = false;
bool IsFinished = false;
private void Update()
{
if(!HasRunned)
{
//Code to be called before one second
HasRunned = true;
}
if (!IsFinished)
Timer += 1 * Time.deltaTime;
if (Timer >= MaxTime)
{
//Code to be called after the one second
IsFinished = true
}
}
This isn't a great solution but I think it works
Hi hirenmakwana,
I'm expecting the Couroutine to run a loop in which some code runs before the WaitForSeconds and some other code runs after the WaitForSeconds. Right now it seems like it's stopping right at the WaitForSeconds. and does not run the second part or reiterate the first one.
Answer by xxmariofer · Jun 01 at 12:09 PM
A. You are deactivating the object with the script attached.
B. You are setting the Time.timeScale to 0
Hi xxmariofer,
neither of both, because
a) the object is always active (I've tried attaching another script to the object with another coroutine I was using before and it works perfectly); b) the Time.Timescale is currently 1 as everything else is working as intended (player movement, other coroutines and so on);
add a log to the update, if the log gets printed, you are 100% canceling the coroutine somewhere else. Remember calling StopAllCoroutines will also stop coroutines from other scripts attach to the same gameobject
void Update()
{
Debug.Log("ENTERS");
}
This is a new script that is not called by anything, also, I'm currently not using StopAllCoroutines but stopping them by name with a manager. Also, this is the only coroutine that uses this name.
Anyway, I found a solution with @Caeser_21 suggestion.
Thanks anyway for your help!