Repeatedly recalculating a value is a common mistake when scripting in Unity, and particularly when it comes to the GetComponent() method. For example, the following script code is trying to check a creature's health value, and if its health goes below 0, it will disable a series of components to prepare it for a death animation:
void TakeDamage() {
Rigidbody rigidbody = GetComponent<Rigidbody>();
Collider collider = GetComponent<Collider>();
AIControllerComponent ai = GetComponent<AIControllerComponent>();
Animator anim = GetComponent<Animator>();
if (GetComponent<HealthComponent>().health < 0) {
rigidbody.enabled = false;
collider.enabled = false;
ai.enabled = false;
anim.SetTrigger("death");
}
}
Each time this poorly optimized method executes, it will reacquire five different component...