Hi, I’m trying to Spawn enemies randomly into 1 of the 4 different spawn points and then once they are destroyed, Wait a random number of seconds and then respawn in another random SpawnPoint which IS NOT already in use. The enemies don’t move and I don’t want them Spawning on top of each other.
So far I’m using this function which currently just spawns an enemy in 1 of the 4 locations when called, but I can’t seem to get my head around the logic of the rest Any help would be appreciated!
void spawnPoints() {
Instantiate (enemy, SpawnPoint[Random.Range(0,4)], Quaternion.identity);
}
Here is a solution. Make a GameManager class that will have a list with your spawn points. Here you’ll instantiate the enemy’s, like this:
class GameManager{
public static List<GameObject> unusedSpawnPoints = new List<GameObject> ();
public GameObject[] spawnPointsPos;
public GameObject enemy;
void Start() {
if (unusedSpawnPoints.Count > 0)
unusedSpawnPoints.Clear ();
foreach(var x in spawnPointsPos) {
unusedSpawnPoints.Add (x);
}
}
void SpawnEnemy() {
if (unusedSpawnPoints.Count < 0)
return;
var spawnPoint = unusedSpawnPoints [Random.Range (0, unusedSpawnPoints.Count)];
var clone = Instantiate (enemy, spawnPoint.transform.position, Quaternion.identity) as GameObject;
unusedSpawnPoints.Remove (spawnPoint);
clone.GetComponent <Enemy> ().spawnPoint = spawnPoint;
}
}
In inspector you’ll have to populate the spawnPointsPos.
After one enemy is instantiated, the position at which it has instantiated is removed from the list.
If you want to instantiate another enemy, his position will be chosen from the remaining spawn points.
The enemy class should look like this:
class Enemy{
public GameObject spawnPoint;
void DestroyEnemy() {
//free the spawnpoint
GameManager.unusedSpawnPoints.Add (spawnPoint);
Destroy (gameObject);
}
}
Before you destroy the enemy, you should free his spawn point by adding it in the list of unused spawn points.
The spawn point could have boolean values for ‘inUse’ and ‘isDestroyed’. Before spawning, you create a new array (list probably) of “Valid Spawn Points” that are acceptable to choose (a simple for-loop adding points that aren’t destroyed or in use).
Then you randomly select one of those spawn points to spawn at (and after spawning, you need to set the bool value of inUse to true).