Performance: Adding and removing components
MEDIUM IMPACT
This affects frame rendering speed and responsiveness by changing the number of active components on GameObjects during gameplay.
void Start() {
cachedRigidbody = gameObject.GetComponent<Rigidbody>();
}
void ToggleRigidbody(bool enable) {
if (enable && cachedRigidbody == null) {
cachedRigidbody = gameObject.AddComponent<Rigidbody>();
} else if (!enable && cachedRigidbody != null) {
Destroy(cachedRigidbody);
cachedRigidbody = null;
}
}void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
gameObject.AddComponent<Rigidbody>();
}
if (Input.GetKeyDown(KeyCode.Backspace)) {
Destroy(gameObject.GetComponent<Rigidbody>());
}
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Add/remove components every frame in Update | Many component adds/removes | Multiple script recompilations | High CPU usage | [X] Bad |
| Add/remove components on explicit events with caching | Few component changes | Single script recompilation per event | Low CPU usage | [OK] Good |