Hey everyone, I am trying to make a space shooter game where enemies spawn repeatedly. I tried to make them spawn after a certain amount of time, but I could not figure it out. I made code below that should spawn 10 enemies repeatedly as well, but the code only spawns one. Can someone help me out?
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour
{
public GameObject [] spawnpoints;
public GameObject Enemy;
private int i;
void Start ()
{
spawnpoints = GameObject.FindGameObjectsWithTag ("Spawnpoint");
i = 1;
while (i < 10)
{
GameObject spawn = spawnpoints [Random.Range (0, spawnpoints.Length)];
Instantiate (Enemy, spawn.transform.position, spawn.transform.rotation);
i = i + 1;
}
}
}
I realized that the loop had no time parameters when I asked the question, and that hurdle was something I tried to overcome when I first started trying to make spawn waves. But I could not figure it out so i decided to break down the problem further by just getting enemies to spawn one after another.
I want the code to make 10 enemies back to back basically. Thats what I mean.
Yeah that video was informative and helpful. Ill go update my code and if I still need help ill post tomorrow I guess. But hopefully this video should be able to help me out a lot.
If you want to spawn enemies at a certain amount of time, you have to use Coroutines.
For example, let’s say that you want to spawn enemies once every 0.5 seconds.
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour
{
public GameObject [] spawnpoints;
public GameObject Enemy;
private int i = 0;
private IEnumerator SpawnEnemies()
{
GameObject spawn = spawnpoints[Random.Range(0, spawnpoints.Length)];
Instantiate(Enemy, spawn.transform.position, spawn.transform.rotation); // I would honestly use Quaternion.identity instead of spawn.transform.rotation, but it is up to you
i++;
yield return new WaitForSeconds(0.5f); // or you can put any amount of seconds in here
if (i < 10) StartCoroutine(SpawnEnemies());
// don't need an else because it won't do anything when the condition is not met
}
void Start ()
{
spawnpoints = GameObject.FindGameObjectsWithTag ("Spawnpoint");
StartCoroutine(SpawnEnemies());
}
}