- Home /
max amount of enemy present?
in this code i spawn from an array of enemy into my game. can someone help me so that i can spawn a max amount of enemy for each type of enemy. and that is spawns them instantly. and if one is destroyed another spawns in
public class enemyspawn : MonoBehaviour { //Array of enemies to spawn public GameObject[] enemy;
//Enemies will be spawned in random positions inside these boundaries
//The minimum x and z position to spawn the enemies
public Vector2 minSpawnPos;
//The maximum x and z position to spawn the enemies
public Vector2 maxSpawnPos;
//The time between enemy spawns
public float spawnRate = 3f;
//The minimum distance to spawn the last spawned enemy
public float minSpawnDistance = 2f;
Vector3 lastSpawnPosition;
float lastSpawn;
private void Update()
{
//Time check to see if it's time to spawn a new enemy
if (lastSpawn + spawnRate < Time.time)
{
SpawnEnemy();
}
}
private void SpawnEnemy()
{
Vector3 spawnPosition;
//Selects a random enemy to spawn from the array of enemies
int enemySpawnIndex = Random.Range(0, enemy.Length);
//Will keep on generating a new spawn position until it's far enough away from the last one
do
{
spawnPosition = new Vector3(Random.Range(minSpawnPos.x, maxSpawnPos.x), Random.Range(minSpawnPos.y, maxSpawnPos.y));
} while (Vector3.Distance(spawnPosition, lastSpawnPosition) < minSpawnDistance);
//Spawns a new instance of an enemy
GameObject instance = Instantiate(enemy[enemySpawnIndex], spawnPosition, Quaternion.identity);
//"Resets" the spawn timer
lastSpawn = Time.time;
//Sets this enemies position as the last spawned enemy
lastSpawnPosition = spawnPosition;
}
}
Answer by Magso · Jan 28, 2020 at 01:08 AM
This can be done with a for loop by setting a variable to how many enemies there should be and checking if FindGameObjectsWithTag length exceeds this value.
var enemies = GameObject.FindGameObjectsWithTag("Enemy");
if(enemies.Length < maximumEnemies)
{
var enemiesNeeded = maximumEnemies - enemies.Length;
for(int i = 0; i < enemiesNeeded; i++)
{
//SpawnEnemy
}
}
Red lines? Compiler error or (I suspect) visual studio red lining a unity specific method like FindGameObjectsWithTag and variable names?
maybe try hard typing ins$$anonymous$$d of using so many vars
Answer by logicandchaos · Jan 28, 2020 at 02:15 PM
int maxEnemies=100;
Start(){
for(int i=0;i<maxEnemies;i++)
Instantiate();
}
Then when an enemy dies instead of destroying it just move it somewhere else, to a spawn location.
Your answer
Follow this Question
Related Questions
Add an offset distance between 2 spawned objects 1 Answer
How to Make an Expanding Spawn Area for Prefabs? 2 Answers
Spawner won't work if I click too fast 0 Answers
Players Not Showing 0 Answers
Having Trouble with Instantiating an object on an axis 2 Answers