Performance: Component communication
This affects frame rate and responsiveness by how often and how many messages or events are sent between components during gameplay.
void Update() {
if (shouldAct) {
otherComponent.DoActionDirectly();
}
}void Update() {
otherComponent.SendMessage("DoAction");
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| SendMessage every frame | N/A | N/A | N/A | [X] Bad |
| Direct method calls on condition | N/A | N/A | N/A | [OK] Good |
| Events invoked every frame | N/A | N/A | N/A | [!] OK |
| Events invoked on state change | N/A | N/A | N/A | [OK] Good |
GetComponent<Type>() is used to get a component on the same GameObject.FindObjectOfType<Type>() searches the whole scene, SendMessage() calls methods by name, and Instantiate() creates new objects, so they are not for direct component access.GetComponent<Type>().public class Player : MonoBehaviour {
private Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
if(rb != null) {
Debug.Log("Rigidbody found");
} else {
Debug.Log("No Rigidbody");
}
}
}GetComponent<Rigidbody>() returns it; otherwise, it returns null.rb is not null and prints "Rigidbody found" if true, else "No Rigidbody".public class Enemy : MonoBehaviour {
void Start() {
Player player = GetComponent<Player>();
player.TakeDamage(10);
}
}GetComponent<Player>() looks for Player on the same GameObject. If Player is not attached, it returns null.player.TakeDamage(10) without checking if player is null will cause a NullReferenceException at runtime.GetComponent<Type>() on it.GetComponent<Type>() on current GameObject won't find other GameObject's components. Calling FindObjectOfType<Type>() every frame is inefficient. Creating components with new is invalid in Unity.Pass the test and this pattern moves unknown