In my game, I have various doorways that act as spawn points for enemies. I'm trying to limit the spawners to only spawning when the player is determined to be within 10 meters of the spawn point (I'm only assuming this is the standard way enemies are randomly spawned in the majority of games... Having never done this before, this is the first way that came to my mind: Looping through each degree of a full 360* circle, determine all colliders within range (in my case, 10 meters) and if one of them is the enemy, spawn an enemy; if not, finish the circle, wait one second and repeat.
The following is my code for this. (With extra commenting just to make it beyond plainly obvious what each line is for, lol) This does have the basic functionality I'm looking for, but since I haven't done it before, I'm curious if this is the best or most efficient way to do what I'm trying to do.
Thanks for the help!
public IEnumerator SpawnAnEnemy() {
while(Player.amIAlive) {
if (EnemyCount < MaxEnemies){
for (float degree = 0; degree <= 360; degree++){
angleToV3Conversion = new Vector3(Mathf.Sin(Mathf.Deg2Rad * degree), 0, Mathf.Cos(Mathf.Deg2Rad * degree)); //CONVERT DEGREE TO A POINT IN 3D SPACE
rayCastHitInfo = Physics.RaycastAll (transform.position, angleToV3Conversion, 10F); //PLOT RAY AT SPECIFIC ANGLE, RETURN ALL HITS IN THAT DIRECTION
for (int hitNumber = 0; (hitNumber < rayCastHitInfo.Length); hitNumber++){ //LOOP THROUGH EACH RETURNED HIT
if (rayCastHitInfo[hitNumber].collider.gameObject.tag == "Player"){ //IF RETURNED HIT WAS PLAYER
Instantiate (enemy, new Vector3(spawnX, spawnY, spawnZ), new Quaternion(spawnXRot, spawnYRot, spawnZRot, 0)); //SPAWN ENEMY AT SPECIFIED LOCATION
EnemySpawner.EnemyCount++;
yield return new WaitForSeconds(1F); //EXIT LOOP FOR ONE SECOND
}
}
}
}
yield return new WaitForSeconds(1F);
}
}//If enemy count is less than maximum & Player in range, spawn enemy, increment count, and wait 1 second--repeat.