I would like something to spawn every 5 second, and i want to be able to change the delay.
Here is the code. The problem happens in Void SpawnTNT
using UnityEngine;
using System.Collections;
public class spawn : MonoBehaviour {
public Transform[] spawnPoint;
public GameObject tnt;
public bool Spawning = true;
// Use this for initialization
void Start () {
SpawnTNT ();
}
// Update is called once per frame
void Update () {
}
void SpawnTNT ()
{
while (Spawning) {
StartCoroutine (Example (1));
Instantiate (tnt, spawnPoint [0].position, Quaternion.identity);
}
}
IEnumerator Example(float delay) {
print(Time.time);
yield return new WaitForSeconds(delay);
print(Time.time);
}
}
StartCoroutine is a regular function call; it starts the coroutine but it returns immediately, i.e. it doesn’t wait for the coroutine to finish. So you’re setting spawning to false, then back to true again, within the same frame.
using UnityEngine;
using System.Collections;
public class spawn : MonoBehaviour {
public Transform[] spawnPoint;
public GameObject tnt;
public bool Spawning = true;
void Start () {
StartCoroutine (SpawnTNT());
}
IEnumerator SpawnTNT () {
while (true) {
print(Time.time);
yield return new WaitForSeconds(1f);
print(Time.time);
if (Spawning)
Instantiate(tnt, spawnPoint[0].position, Quaternion.identity);
}
}
}