- Home /
Question by
AshwinTheGammer · Apr 08, 2020 at 12:43 PM ·
physicstransformspawnpointsoverlapsphereenemy spawn
Overlapsphere isn't working as expected.
I've a scene in which I've an empty gameobject(spawnPoints). it contains all the spawnpoint for spawning of enemy. PURPOSE and PROBLEM I don't want to overlap the enemies. There are total 6 spawn points. If I put 5 as the size of spawn point. Everything works fine...i.e, enemies don't overlap. But if I put 7, 8 or 9 as the size of spawnpoint array. enemies overlaps. I'm using Physics.overlapsphere for detection of the colliders.
I don't want to spawn the enemies if there is no place to spawn. If there is no place to spawn then I want the enemies to wait...until any spawn point is clear.
CODE
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemySpawns : MonoBehaviour {
public GameObject Enemy;
public Transform[] spawnPoints;
public float spawnTime;
public int maxEnemy = 5;
private int currentEnemy = 0;
bool isSpawn;
public float EnemyRadius = 16f;
void Start(){
isSpawn = false;
InvokeRepeating ("spawnEnemy", spawnTime, 5.4f);
isSpawn = true;
}
public void spawnEnemy(){
for (int i = 0; i < spawnPoints.Length; i++) {
Collider[] cols = Physics.OverlapSphere (spawnPoints [i].transform.position, EnemyRadius);
foreach (Collider hit in cols) {
if (hit.tag == "AI Controller") {
isSpawn = false;
return;
} else {
isSpawn = true;
}
}
}
if (isSpawn == true) {
if (currentEnemy <= maxEnemy) {
Transform currentSpawnPoint = spawnPoints [Random.Range (0, spawnPoints.Length)].transform; //pickrandom
Instantiate (Enemy, currentSpawnPoint.position, currentSpawnPoint.rotation);
currentEnemy++;
}
}
if (currentEnemy == maxEnemy) { //stop spawning enemies
CancelInvoke ();
}
}
}
Comment