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?
Also click-and-drag the "Create Instance" icon from "Main1" tab. Choose the enemy you want to spawn from the "Object" drop-down menu and enter the X and Y coordinates where you want the enemy to spawn. Click "OK." Open the room you want the enemies to appear in.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With