First game; Game Manager Question; Spawning enemies!

Working on my first game in Unity 3, a top-down shooter. Nothing too fancy. I have 8 off-screen spawn points littered about…I’m not really sure where to go from here. I can’t really tell “How” I should do this. Obviously, theres more than one way, but I don’t really know where to start.

I have the spawn points put into an array with GameObject.FindGameObjectsWithTag("spawnpoint"); but that’s about it. How do I utilize my new array? What can I do with it? Suppose I wanted to send an enemy from a random spawnpoint listed in the array. Where would I call that? In the Update function, perhaps? I hope someone can point me in the right direction!

What I want to have happen is: Be able to choose a spawn point for a given enemy (or even have a loop to cycle through points and spawn them for me) and have it fly toward the player.

Also: I’m coding in javascript.

PS: I’m not necessarily asking for someone to simply write some code - if someone could help explain by way of example and sample code, that would be much better :slight_smile: Thanks!

A simple trick is to create an empty game object, call it “Enemies” and attach the spawning script to it. To keep control of how many enemies are currently alive, child each enemy created to “Enemies” and use transform.childCount to know how many they are:

var enemyPrefab: Transform;
var maxEnemiesAlive: int = 10;
var maxEnemies: int = 30;
private var totalEnemies: int;
private var spawnPoints: GameObject[];
private var player: Transform;

function Start(){
  spawnPoints = GameObject.FindGameObjectsWithTag("spawnpoint");
  player = GameObject.FindWithTag("Player").transform;
  totalEnemies = maxEnemies; // define how many enemies the level has
}

function Update(){
  // when some enemy is killed and total enemies isn't zero yet...
  if (transform.childCount < maxEnemiesAlive && totalEnemies > 0){
    // draw a random spawn point:
    var pos = spawnPoints[Random.Range(0, spawnPoints.length)].transform.position;
    // find a rotation to look at the player:
    var rot = Quaternion.LookRotation(player.position - pos);
    // create the new enemy facing the player:
    var enemy = Instantiate(enemyPrefab, pos, rot);
    // child it to Enemies (this object):
    enemy.parent = transform;
    totalEnemies--; // decrement the remaining enemies
  }
}

This basic code instantiate enemies whenever the current population falls below maxEnemiesAlive, and create them facing the player. You can add a script to the enemy prefab to make it go forward, or chase the player. You can also add a Destroy(enemy.gameObject, someTime) right after its creation, so it will die when the specified time has ellapsed.