- Home /
Question by
b2hinkle · Jun 10, 2018 at 02:34 AM ·
c#randomspawnrandom.rangerandomspawning
How to make enemy prefab spawn at random times between 1.0f to 10.0f.
I am trying to make my enemy prefab spawn from a spawn point (which I have already achieved) at random times between 1.0f to 10.0f. Here is my code right now.........
{
public GameObject prefabToSpawn;
float spawnTime;
private void Start()
{
spawnTime = Random.Range(0.0f, 10.0f);
InvokeRepeating("Spawn", 5f, spawnTime);
}
void Spawn()
{
Instantiate(prefabToSpawn, transform.position, Quaternion.identity);
Debug.Log("enemy spawned");
}
}
Right now the code successfully randomly picks a number between 1 and 10 and uses that as the time to spawn the enemies one after the other, but the thing is is that once it chooses a random value between 1 and 10, the value is always the same, and therefore there is no randomness to the enemies' spawn time one after the other.
I would like the value of "spawnTime" to change to a new value (from 1.0f to 10.0f) every time after the prefab is spawned.
Comment
Answer by SlowCircuit · Jun 10, 2018 at 03:42 AM
Use a coroutine. https://docs.unity3d.com/Manual/Coroutines.html
IEnumerator SpawnEnemies() {
float SpawnTimer;
while (true) {
SpawnTimer = Random.Range(1f, 10f);
yield return new WaitForSeconds(SpawnTimer);
// Actual spawning goes here
}
}