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 references. This is not very friendly on CPU usage. This is particularly problematic if the main method was called...