Reputation: 59
I am looking to get enemies to spawn at a random interval between 5 and 15 seconds.
Here is the code I have now. I have the move/transform script on the prefab enemy.
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
public float spawnTime = 5f; // The amount of time between each spawn.
public float spawnDelay = 3f; // The amount of time before spawning starts.
public GameObject[] enemies; // Array of enemy prefabs.
public void Start ()
{
// Start calling the Spawn function repeatedly after a delay .
InvokeRepeating("Spawn", spawnDelay, spawnTime);
}
void Spawn ()
{
// Instantiate a random enemy.
int enemyIndex = Random.Range(0, enemies.Length);
Instantiate(enemies[enemyIndex], transform.position, transform.rotation);
}
}
This currently spawns enemies every 3 seconds. How can I spawn an enemy every 5 to 15 seconds?
Upvotes: 5
Views: 17574
Reputation: 20048
For such a case you might want to make use of a WaitForSeconds call. It is a YieldInstruction which will suspend a coroutine for a certain period of time.
So you create a method to perform the actual spawning, make that a coroutine, and before you do the actual instantiation, you wait for your random period of time. That would look something like this:
using UnityEngine;
using System.Collections;
public class RandomSpawner : MonoBehaviour
{
bool isSpawning = false;
public float minTime = 5.0f;
public float maxTime = 15.0f;
public GameObject[] enemies; // Array of enemy prefabs.
IEnumerator SpawnObject(int index, float seconds)
{
Debug.Log ("Waiting for " + seconds + " seconds");
yield return new WaitForSeconds(seconds);
Instantiate(enemies[index], transform.position, transform.rotation);
//We've spawned, so now we could start another spawn
isSpawning = false;
}
void Update ()
{
//We only want to spawn one at a time, so make sure we're not already making that call
if(! isSpawning)
{
isSpawning = true; //Yep, we're going to spawn
int enemyIndex = Random.Range(0, enemies.Length);
StartCoroutine(SpawnObject(enemyIndex, Random.Range(minTime, maxTime)));
}
}
}
Give it a try. That should work.
Upvotes: 7