Performance: Adding and removing components
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 |
AddComponent<Type>() method do in Unity?player?var enemy = new GameObject("Enemy");
var rb = enemy.AddComponent<Rigidbody>();
Destroy(rb);var obj = new GameObject(); obj.AddComponent<BoxCollider>(); Destroy(obj.GetComponent<BoxCollider>);
Pass the test and this pattern moves unknown