Why we dont call it, at CanAttack() Method

why we dont just use this method (in Figther.cs) to stop the aiattack instead of AIController.cs?

 public bool CanAttack(GameObject combatTarget)
        {
            if (combatTarget == null) { return false; }
            **if(GetComponent<Health>().IsDead()) {return false;}**
            Health targetToTtest = combatTarget.GetComponent<Health>();
            return targetToTtest != null && !targetToTtest.IsDead();
        }

You can, if you ensure that all CombatTargets have Health components…
The method Rick used assures null checking, and avoids repeating GetComponents.

There are many ways to the same result. If you’re using later versions of Unity, this can be safely condensed to one (long line:

return combatTarget && combatTarget.TryGetComponent(out Health test)?!test.IsDead():false;

Everything before the if statement checks and validates that the combatTarget exists and has a health component. This creates a temporary Health reference which is used in the statement immediately after the ?, in this case returning !test.IsDead(), if the target is null or has no Health component, then the part after the : is returned, false.

I believe Sam later adjusts this method to also account for the target to be reachable via the NavMesh, so while my little one liner looks spiffy, the method will get more complex in a later lecture and my one liner won’t work quite as well anymore.

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

Privacy & Terms