A common mistake when scripting in Unity is to overuse 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
, disable a series of Components to prepare it for a death animation:
void TakeDamage() { if (GetComponent<HealthComponent>().health < 0) { GetComponent<Rigidbody>().enabled = false; GetComponent<Collider>().enabled = false; GetComponent<AIControllerComponent>().enabled = false; GetComponent<Animator>().SetTrigger("death"); } }
Each time this method executes, it will reacquire five different Component
references. This is good in terms of heap memory consumption (in that it doesn't cost any), but it is not very friendly on CPU usage. This is particularly problematic if the main method were called during Update()
. Even if it is not, it still might coincide with other important events, such as creating particle effects,...