I didn’t like the idea of the NextFreePosition method being so linear, so decided to have a play with randomising the next spawn point, I came up with the below and thought it may help someone else
Also has my take on grabbing the enemy ships to see if all enemies are dead
Just be sure to tag your Position and Enemy Ship prefabs with the appropriate tags.
Transform NextFreePosition()
{
GameObject[] positions = GameObject.FindGameObjectsWithTag("EnemySpawn");
RandomizeArray(positions);
foreach (GameObject position in positions)
{
if (position.transform.childCount == 0)
{
return position.transform;
}
}
return null;
}
bool AllEnemiesDead()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("EnemyShip");
if (enemies.Length > 0)
{
return false;
} else {
return true;
}
}
void RandomizeArray(GameObject[] array)
{
for (var i = array.Length - 1; i > 0; i--)
{
var r = Random.Range(0, i);
var tmp = array[i];
array[i] = array[r];
array[r] = tmp;
}
}