- Home /
How can I make sure my GameObjects don't spawn on top of each other, and that only a certain number remain in the scene at one time?
,This is my first attempt at a game and it's a pretty simple one. I've got a ball that you can control around the scene and enemies that spawn every couple of seconds. So far I can control my character and I can spawn the enemies within the scene at random positions. However they spawn on top of each other, I'm also trying to find a way to limit the number of enemies in the scene, so for example once 10 enemies get spawned the first one to spawn get's despawned, followed by the second etc. So the maximum number of enemies in the scene at one time is 10.
My Spawnerscript so far, the enemies have got box colliders:
public class EnemySpawnerScript : MonoBehaviour
{
public GameObject enemy;
public GameObject enemy2;
public GameObject enemy3;
public GameObject[] enemyArray;
float randX;
float randY;
Vector2 whereToSpawn;
public float spawnRate = 2f;
float nextSpawn = 0.0f;
int RandomOption;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
//Random Postion
randX = UnityEngine.Random.Range(-2.5f, 2.5f);
randY = UnityEngine.Random.Range(-4.8f, 4.8f);
whereToSpawn = new Vector2(randX, randY);
//Random enemyObject sprite
GameObject[] enemyArray = { enemy, enemy2, enemy3 };
RandomOption = UnityEngine.Random.Range(0, enemyArray.Length);
//Instantiate
Instantiate(enemyArray[RandomOption], whereToSpawn, Quaternion.identity);
}
}
}
Answer by Klarzahs · Oct 06, 2020 at 04:12 PM
Hi @bobmcdonal
Not spawning ontop:
You can either check that the new random position isn't close to already existing positions:
Vector3.Distance(enemy1.transform.position, enemy2.transform.position) < ENEMY SIZE
Or you can delete all colliding enemies. For that, have a look at this tutorial, as it is a bit more complex.
Maximum enemies:
Use a list, where you store all your created enemies. If you want to create a new one, check if the list contains the max amount. If so, get the first one and simply reset it to the new position (you might have to reset ammunition, hitpoints etc)
Your answer
Follow this Question
Related Questions
How do I add multiple different enemies to a wave spawner? 2 Answers
How to spawn objects but set a cap of how many can be alive at the same time? 0 Answers
Enemy Spawn System with time and limit enemy in game 2 Answers
c# problem with limiting rotation (with rigidbody) 1 Answer
I cannot store data into PlayerPrefs after a certain amount of data 2 Answers