How do I make the enemies continue spawning?
When I press play the spawner only spawns 1 enemy and thats it. How do I make it continuous?
Here's my Spawner script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public Transform[] spawnLocations;
public GameObject[] whatToSpawnPrefab;
public GameObject[] whatToSpawnClone;
// Use this for initialization
void Start ()
{
Spawn();
}
// Update is called once per frame
void Spawn ()
{
whatToSpawnClone[0] = Instantiate(whatToSpawnPrefab[0], spawnLocations[0].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
whatToSpawnClone[1] = Instantiate(whatToSpawnPrefab[1], spawnLocations[1].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
whatToSpawnClone[2] = Instantiate(whatToSpawnPrefab[2], spawnLocations[2].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
}
}
Answer by PizzaPie · Apr 06, 2017 at 10:52 AM
There are 3 basic ways to go with this. 1st use Invoke like this:
void Start()
{
InvokeRepeating("Spawn", 0f, 5f);
}
this will call spawn every 5 seconds
2nd use a coroutine something like this:
WaitForSeconds wfs = new WaitForSeconds(5f);
//...
void Start(){
StartCoroutine(Spawn())
}
IEnumerator Spawn()
{
while (true)
{
for (int i = 0; i < 3; i++)
{
whatToSpawnClone[i] = Instantiate(whatToSpawnPrefab[i], spawnLocations[i].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
}
yield return wfs;
}
}
This will do the same as above but it has some performance benefits, make sure to replace the Spawn() with the one from here.
3rd is to use Update(), something like this:
float delay = 5f;
float timeToSpawn;
void Start()
{
timeToSpawn = Time.time;
}
void Update()
{
if(timeToSpawn < Time.time)
{
Spawn();
timeToSpawn = Time.time + delay;
}
}
To conclude i would personally use the coroutine but the invoke is the easiest in terms of syntax as for the last i wouldn't recommend it at all. Cheers hope that helps.
Note: to stop the coroutine use this: StopCoroutine(Spawn()); and to stop the Invoke use : CancelInvoke("Spawn");
Thanks and quick question, I bake the nav and put agents on enemies but the enemies spawn in the terrain
Probably you should spawn them a bit above the ground.
I have done that but they still spawn in the terrain. Same goes for the player.