- Home /
Multiple spawn points (C#)
I'm trying to tackle the logic for the following setup:
I have multiple spawn points (bases) that can be destroyed and then become inactive. How many are there changes from level to level.
These spawn points spawn enemies randomally until a certain number of enemies exists in the world (say 20). It would then not spawn any more enemies until some of the existing ones are destroyed by the player.
Are there any existing tutorials for something like that (preferably C#)? Any pointers will be much appreciated.
Answer by aldonaletto · Mar 07, 2012 at 05:07 PM
A simple solution to control the enemy population is to create an empty object - let's call it "Enemies" - reset its position and rotation, then child every created enemy to it. The spawning script is attached to the Enemies object, and contains an array with the bases. The enemy count is the Enemies childCount property, and is compared to maxEnemies each Update: when it's lower than the maxEnemies value, one of the bases is randomly selected, and the new enemy is instantiated at that position and childed to Enemies. If the base has been destroyed, its reference is null, and the script does nothing - a new base will be randomly selected in the next Update.
public Transform[] bases; // drag the bases here public float offSet = 1.5f; // height at which the enemy is created public Transform enemyPrefab; public int maxEnemies = 20;
void Update(){ if (transform.childCount < maxEnemies){ // if less than maxEnemies... // select a random base: Transform base = bases[Random.Range(0, bases.Length)]; if (base){ // if the selected base doesn't exist, try again next Update // calculate position: base location plus vertical offset: Vector3 pos = base.position + offSet * Vector3.up; // instantiate the enemy... Transform enemy = Instantiate(enemyPrefab, pos, Quaternion.identity) as Transform; // and child it to Enemies: enemy.parent = transform; } } } NOTE: I usually write in JS, thus the code above may have stupid C# errors!
Answer by Julien-Lynge · Mar 07, 2012 at 04:40 PM
@Michael_8
I would start by looking at the search results on this site:
http://answers.unity3d.com/search.html?redirect=search%2Fsearch&q=multiple+spawn+point
A number of which have example code and ideas.