- Home /
Enemies spawn on top of each other(C#)(Unity)
Good day, i'm having an issue with an enemy random spawner code. problem is that i got two enemies but when they spawn sometimes they spawn on top of each others. some1 know how to fix it? here is code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public GameObject Enemy;
public GameObject Enemy2;
float maxSpawnRateInSeconds = 5f;
void SpawnEnemy()
{
Vector2 min = Camera.main.ViewportToWorldPoint (new Vector2 (0, 0));
Vector2 max = Camera.main.ViewportToWorldPoint (new Vector2 (1, 1));
GameObject anEnemy = (GameObject)Instantiate (Enemy);
anEnemy.transform.position = new Vector2 (Random.Range (min.x, max.x), max.y);
GameObject anEnemy2 = (GameObject)Instantiate (Enemy2);
anEnemy2.transform.position = new Vector2 (Random.Range (min.x, max.x), max.y);
ScheduleNextEnemySpawn();
}
void ScheduleNextEnemySpawn ()
{
float spawnInNSeconds;
if(maxSpawnRateInSeconds > 1f)
{
spawnInNSeconds = Random.Range(1f, maxSpawnRateInSeconds);
}
else
spawnInNSeconds = 1f;
Invoke ("SpawnEnemy", spawnInNSeconds);
}
void IncreaseSpawnRate()
{
if(maxSpawnRateInSeconds > 1f)
maxSpawnRateInSeconds--;
if(maxSpawnRateInSeconds == 1f)
CancelInvoke("IncreaseSpawnRate");
}
public void ScheduleEnemySpawner()
{
maxSpawnRateInSeconds = 5f;
Invoke ("SpawnEnemy", maxSpawnRateInSeconds);
InvokeRepeating ("IncreaseSpawnRate", 0f, 30f);
}
public void UnscheduleEnemySpawner()
{
CancelInvoke("SpawnEnemy");
CancelInvoke("IncreaseSpawnRate");
}
}
Comment
Answer by boss2070301 · May 20, 2020 at 12:20 AM
This is the code I use in my game. @Apkar007
public float spawnRadius = 7f, time = 1.5f;
public GameObject enemy;
void Start()
{
StartCoroutine(SpawnAnEnemy());
}
IEnumerator SpawnAnEnemy()
{
Vector2 spawnPos = GameObject.Find("Player").transform.position;
spawnPos += Random.insideUnitCircle.normalized * spawnRadius;
Instantiate(enemy, spawnPos, Quaternion.identity);
yield return new WaitForSeconds(time);
StartCoroutine(SpawnAnEnemy());
}
Your answer
Follow this Question
Related Questions
AI spawning areas. What are the ways to make them? 1 Answer
Generate gameObject horde, more positioned towards front of horde 1 Answer
How to make enemy prefab spawn at random times between 1.0f to 10.0f. 1 Answer
How to create random spawn for an object? (C#) 0 Answers
How to spawn random buildings 5 Answers