I’ve been trying to spawn enemies withing a radius around my player. I’m able to do this but sometimes the enemies will spawn on a part of my terrain that doesn’t have a Navmesh on it, the enemies then cause errors because they can’t get to the player. I’ve been trying to get my enemies to only spawn on parts of the terrain that will allow them to go to the player but have found an inefficient solution. The way my code works right now it will try 800-4000 random locations until it can spawn enough enemies, this causes lag and is obviously not a great way of doing it. I’m probably misusing NavMesh.SamplePosition so any help would be appreciated, everything I’ve found so far about it is very vague.
Code in C#
using UnityEngine;
using System.Collections;
public class EnemySpawner : MonoBehaviour
{
public GameObject player, zombiePrefab, zombie, parent;
public float radius = 10f;
public int zombieNamePostfix = 0;
public int maxZombies, minZombies;
Vector3 SpawnPos = new Vector3(0, 0, 0);
void SpawnEnemy()
{
bool areaIsOnMap = false;
while (!areaIsOnMap)
{
float playerX = player.transform.position.x;
float playerZ = player.transform.position.z;
SpawnPos.x = Random.Range(playerX - radius, playerX + radius);
SpawnPos.z = Random.Range(playerZ - radius, playerZ + radius);
SpawnPos.y = Terrain.activeTerrain.SampleHeight(SpawnPos) + 2.0f;
NavMeshHit hit;
areaIsOnMap = (NavMesh.SamplePosition(SpawnPos, out hit, 1.0f, NavMesh.AllAreas));
print(areaIsOnMap);
}
GameObject zombie = Instantiate(zombiePrefab, SpawnPos, Quaternion.identity) as GameObject;
zombie.transform.parent = parent.transform;
zombie.name += zombieNamePostfix;
print(SpawnPos.ToString() + areaIsOnMap.ToString() + zombie.name);
zombieNamePostfix++;
zombie.GetComponent<UnityStandardAssets.Characters.ThirdPerson.AICharacterControl>().target = player.transform;
}
void Update()
{
if (parent.transform.childCount < minZombies)
{
int zombiesToSpawn = Random.Range(minZombies - parent.transform.childCount, maxZombies - parent.transform.childCount);
int counter = 0;
while (counter <= zombiesToSpawn)
{
counter++;
SpawnEnemy();
}
}
}
}
Thanks in advance, fleap.