Problem with yield return new waitForSeconds...

Hey there,
I have a Problem with the “yield return new waitForSeconds…” on Line 17. Everything works fine til I call the yield… I added a Debug.Log(…); in the Line bevor the call and one after. After coming to the yield it doesn’t do anything else… I even added an enormeous while-loop before it and it went through the whole loop, so no stopping from outside I assume…
Thanks for your help,
Btother

using System.Collections;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public GameObject[] objsToSpawn;
public Transform[] spawnPlaces;
public float minWait = .3f;
public float maxWait = 1f;
public void Start()
{
     StartCoroutine(SpawnFruits());
}
private IEnumerator SpawnFruits()
{
     while (true)
     {
         yield return new WaitForSeconds(Random.Range(minWait, maxWait));
         Transform t = spawnPlaces[Random.Range(0, spawnPlaces.Length)];
         float zRotation = Random.Range(-2, 2);
         if (t == spawnPlaces[0])
         t.transform.Rotate(new Vector3(0, 0, zRotation));
         GameObject go;
         float p = Random.Range(0, 100);
         if (p < 20)
             go = objsToSpawn[0];
         else
             go = objsToSpawn[Random.Range(1, objsToSpawn.Length)];
         GameObject fruit = Instantiate(go, t.position, go.transform.rotation);
         fruit.GetComponent<Rigidbody2D>().AddForce(t.transform.up * Random.Range(10f, 15f), ForceMode2D.Impulse);
         if (t == spawnPlaces[0])
                t.transform.Rotate(new Vector3(0, 0, -zRotation));
         Destroy(fruit, 5f);
     }
}
}

I copied your code and stripped it down to get to yield and put a debug after it. It works fine for me. Make sure your public properties for minWait and maxWait hasn’t been overridden by the inspector

Any chance you’ve got Time.timeScale set to 0?

Actually yes, it’s when I stop the game for “Game over”…

then try this one

2 Likes

Thanks a lot, at least they spawn again… Now I can focus on why the …AddForce is not working, coding is so much fun :smile:

If time is paused (Time.timeScale = 0), Physics is paused too. If you need things to keep moving on your game over screen, you probably want to keep timeScale at 1, and just find some other way to ignore user inputs.