Approach to AggrevateNearbyEnemies

Hi I am just wondering if the solution Sam ran through for this lecture has any difference from my solution which was:

void AggrevateNearbyEnemies()
        {
            RaycastHit[] hits = Physics.SphereCastAll(transform.position, shoutDistance, Vector3.up, 0);
            
            foreach (RaycastHit hit in hits)
            {
                AIController[] enemies = hit.transform.GetComponents<AIController>();
                foreach(AIController enemy in enemies)
                {
                    enemy.Aggrevate();
                }
            }
        }

I suspect Sam’s will have better performance?

Each hit should have either 1 or 0 AIControllers on them. There’s no need to make this an array, as there will only be 1 or 0 elements in it.

This means we can simplify the loop, using only one foreach:

foreach (RaycastHit hit in hits) //each hit is a single GameObject with a collider... 
{
    AIController enemy = hit.transform.GetComponent<AIController>();
    if(enemy)
    {
          enemy.Aggrevate();
    }
}

Ah of course that makes sense, thank you for clarifying so quickly!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms