Health reference in Hit() animation event

In the lecture, the Hit() method is written as:

void Hit()
    {
        Health healthComponent = target.GetComponent<Health>(); // Line 1
        healthComponent.TakeDamage(weaponDamage); // Line 2 
    }

Is there an advantage to creating healthComponent on the first line, then calling TakeDamage() on the second? Is this an example of caching the GetComponent<Health>() call for performance? Or maybe a future lecture will use healthComponent again?

Is there a reason not to use the single line version here?

target.GetComponent<Health>().TakeDamage(weaponDamage);
1 Like

Either method will work.

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

Privacy & Terms