My enemy SpawnManager class which is attached to an empty game object. The problem is in the initial spawning (not the respawning) that it’s just spawning the enemy clones at the (0,0) point in world space.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemySpawner : MonoBehaviour {
public float minSpawnDensity = 6f;
public float minSpawnDistance = 20f;
public float spawnDistance = 50.0f;
public static List<BaseEnemy> totalEnemy = new List<BaseEnemy>();
public static List<BaseEnemy> deadEnemy = new List<BaseEnemy>();
public GameObject enemy;
private int maxEnemyCount = 6;
private float respawnDelay = 10f;
private Vector3 lastSpawnPoint = Vector3.zero;
private Vector3 spawnPoint = Vector3.zero;
void Update(){
while(totalEnemy.Count < maxEnemyCount){
SpawnEnemy(maxEnemyCount - totalEnemy.Count);
}
for(var i = 0; i < deadEnemy.Count; i++){
BaseEnemy enemy = deadEnemy[i];
float time = Time.time - enemy.timeOfDeath;
if(time > respawnDelay)
{
enemy.gameObject.SetActive(true);
enemy.isAlive = true;
enemy.gameObject.rigidbody.WakeUp();
enemy.gameObject.GetComponent<Animator>().enabled = true;
enemy.gameObject.GetComponentInChildren<EnemyAI>().enabled = true;
enemy.SetupEnemy();
deadEnemy.RemoveAt(i);
i--;
}
}
}
private void SpawnEnemy(int numberOfEnemy) {
for(int enemyCount = 0; enemyCount < numberOfEnemy; enemyCount++){
do {
spawnPoint = Random.insideUnitCircle.normalized * spawnDistance;
spawnPoint.y = TerrainHeight(spawnPoint);
} while(IsInvalidSpawnPoint(spawnPoint, lastSpawnPoint));
GameObject clone;
clone = (GameObject) Instantiate(enemy, spawnPoint, transform.rotation);
totalEnemy.Add(clone.GetComponent<BaseEnemy>());
lastSpawnPoint = spawnPoint;
}
}
private bool IsInvalidSpawnPoint(Vector3 spawnPoint, Vector3 lastSpawnPoint){
return spawnPoint.y == Mathf.Infinity || (spawnPoint - lastSpawnPoint).magnitude <= minSpawnDensity || spawnPoint.magnitude <= minSpawnDistance;
}
private float TerrainHeight(Vector2 spawnPoint){
RaycastHit hitPoint;
if(Physics.Raycast(spawnPoint, Vector3.up, out hitPoint)){
return hitPoint.transform.position.y;
}
else if(Physics.Raycast(spawnPoint,Vector3.down, out hitPoint)){
return hitPoint.transform.position.y;
}
else{
return Mathf.Infinity;
}
}
}