0
0
Unityframework~8 mins

Adding and removing components in Unity - Performance & Optimization

Choose your learning style9 modes available
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.
Dynamically adding or removing components during gameplay
Unity
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;
  }
}
Add or remove components only when necessary and cache references to avoid repeated costly calls.
📈 Performance GainReduces CPU spikes by limiting component changes to explicit events, not every frame.
Dynamically adding or removing components during gameplay
Unity
void Update() {
  if (Input.GetKeyDown(KeyCode.Space)) {
    gameObject.AddComponent<Rigidbody>();
  }
  if (Input.GetKeyDown(KeyCode.Backspace)) {
    Destroy(gameObject.GetComponent<Rigidbody>());
  }
}
Adding or removing components inside Update causes frequent CPU spikes and possible frame drops.
📉 Performance CostTriggers multiple script recompilations and internal Unity overhead per frame when keys are pressed.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Add/remove components every frame in UpdateMany component adds/removesMultiple script recompilationsHigh CPU usage[X] Bad
Add/remove components on explicit events with cachingFew component changesSingle script recompilation per eventLow CPU usage[OK] Good
Rendering Pipeline
Adding or removing components affects the scripting and physics update stages, causing Unity to recompile scripts and update internal component lists.
Script Execution
Physics Update
Garbage Collection
⚠️ BottleneckScript Execution due to component initialization and destruction overhead
Core Web Vital Affected
INP
This affects frame rendering speed and responsiveness by changing the number of active components on GameObjects during gameplay.
Optimization Tips
1Avoid adding or removing components inside Update or other frequent loops.
2Cache component references to minimize repeated GetComponent calls.
3Batch component changes and trigger them only on explicit gameplay events.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance cost of adding components every frame in Unity?
AFrequent script recompilation and CPU spikes
BIncreased GPU load
CMore memory allocated for textures
DSlower network communication
DevTools: Unity Profiler
How to check: Open Unity Profiler, record gameplay, filter by 'Scripts' and 'GC', look for spikes during component add/remove calls
What to look for: High spikes in CPU usage and garbage collection during component changes indicate performance issues