Yield Return New WaitForSeconds in while loop not working?

I’ve tried to log into the answers section of this website, but it says something about an internal error so I’m posting here.

EDIT: I have solved my issue almost immediately after posting this thread. I’m sorry for posting this thread when I didn’t need to. I have been looking for this issue for the longest time. It turned out that my int value spawnDelay wasn’t actually being initialized in the start function. I looked at the code here in the thread that I posted and I noticed that I had to edit the start function and it didn’t tick in my head until now. I added “spawnDelay = 3;” in the start function. The reason it wasn’t working was because spawnDelay wasn’t initialized, and I wasn’t getting any errors from it. Strange… Oh well. Problem solved :slight_smile:

I’m having a game breaking issue where my WaitForSeconds isn’t working in my function in my while loop. My other waitforseconds work just fine outside of the while loop in the same function. so enough talking here is my syntax:

public int spawnDelay;

void Start() {
     spawnDelay = 3;
     StartCoroutine(spawn());
}

private IEnumerator spawn() {
      
         // stuff happens here

         // Spawn loop //
         while (true) {
          
         // Stuff happens here

         if(enemies.Length < spawnCount) {
              spawnEnemy(enemyPath, range, enemyHealth, enemyDamage, enemySpeed);
         }

         Debug.Log("delay started"); // Instead of being fired slowly.
         // This is fired once every frame.

         // THIS IS WHAT ISN'T WORKING
         yield return new WaitForSeconds(spawnDelay);

         Debug.Log("delay ended"); // Instead of being fired slowly.
         // Again, this is fired once every frame.
    }
}

Note: There is ONLY ONE reference to this function which is in the start function. There is NOT an update function referencing this script. I’m using VS 2015 as my IDE and it only shows one reference to this function which is coming from its own start function.

1 Like

Your spawnDelay was being initialized by Unity. Since it is public it was automatically being shown in the inspector, and assigned that value, which I’m sure you had set to the default 0.

1 Like

It’s set in Start, which overrides the public field. Not that you should have something both in a public field and in start, but that’s another issue.

@Tamoya , the code as it’s there should work. Could you post the entire thing?

1 Like

I think you missed his edit, originally he didn’t have that initialization in Start, I just wanted to explain why that wouldn’t error. Maybe would be a warning in VS?

I got it working. You have been reading this thread as I was updating with the EDIT.

Thank you for explaining more in detail as to why I wasn’t getting any errors. This is something that I will be looking for in the future before coming to the forums :).

Learning something new everyday :slight_smile:

1 Like