- Home /
random spawn for multible objects
I am making a top-down 2d game and i want to spawn enemies in a certain location. i would also be good if the objects didn't spawn in each other or next. I want to spawn multiple enemy types as well
Answer by W01Fi3 · Jan 25, 2020 at 08:22 AM
Here is a simple script that will spawn a random enemy from an array of enemies, in a random position defined by min and max positions (a square area), while making sure it doesn't spawn too close to the last spawned enemy, but does not check the area it will spawn.
using System.Collections;
using UnityEngine;
public class EnemySpawner : 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 y position to spawn the enemies
public float ySpawnPos = 1;
//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), ySpawnPos, 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;
}
}
Obviously this was a hastily made script that does most of what you ask, but hopefully this helps anyways ^w^
Your answer
Follow this Question
Related Questions
Spawning random prefabs at random spawn points (C#) 0 Answers
How to spawn enemies at different locations and avoid overlapping each other 2 Answers
What is the most efficient way to spawn objects with probability weights in this scenario? 2 Answers
How Increase And Decrease And Reset Spawn Rate Over 0 Answers
,Getting a Spawner Manager Script to reference a Spawner 1 Answer