Hi there,
I’m having a lot of trouble with my field of view check in my game, I’m at the point where I’m questioning if it’s a Unity bug rather than a code error.
The script itself creates a list of objects within the radius, on layer Entities. It then checks to create another list of entities that don’t belong to the “searching” tribe. If that list != 0 it has seen an enemy and therefore switches to attack.
The problem…
It’s scanning and returning as correct, for about 15 seconds before it totally breaks and stops returning anything…
Anyone have any ideas or critique of my code that might help?
You’re all great.
Goji
IEnumerator FieldOfViewCycle()
{
while (true)
{
if (debugMode)
{
Debug.Log("Fired Fov method");
}
FieldOfViewCheck();
// adding a delay to reduce weight on CPU
yield return new WaitForSeconds(0.3f);
}
}
void FieldOfViewCheck()
{
// Create an array of everything we can see labelled entity
// including our own tribe
Collider[] entitiesWithinRange = Physics.OverlapSphere(transform.position, radius, entities);
// DEBUGGING NOTE: at this stage it still breaks anyway
if (debugMode)
{
Debug.Log(entitiesWithinRange.Length);
}
if (entityAI != null)
{
if (entitiesWithinRange.Length != 0)
{
// Creating a new list each time we scan
List<Collider> enemiesWithinRange = new List<Collider>();
// We check every collider we can see that's labelled entity
foreach (Collider entity in entitiesWithinRange)
{
// if an entity, does not belong to our tribe,
// we add it to our enemiesWithinRange list
if (entity.gameObject.GetComponent<EntityAI>().followerManager
!= gameObject.GetComponent<EntityAI>().followerManager)
{
enemiesWithinRange.Add(entity);
}
}
// If our enemiesWithinRange list is greater than 0, we have found
// an enemy and therefore should start hunting
if (enemiesWithinRange.ToArray().Length != 0)
{
entityAI.SetHuntingTarget
(enemiesWithinRange[Random.Range
(0, Random.Range(0, enemiesWithinRange.ToArray().Length))].transform);
entityAI.SwitchState(entityAI.warState);
}
// otherwise, we must not be able to see anyone anymore and therefore
// go back to following our tribe leader
else
{
entityAI.SwitchState(entityAI.followingState);
}
}
}
}