In this lesson, you will learn how to replace high-frequency Update polling with event-driven logic to eliminate unnecessary CPU cycles.
The Problem with Polling
In many game architectures, we fall into the trap of checking conditions every frame. For example, a PlayerHealthUI script might use Update() to check if the player's health has changed:
void Update() {
// This runs 60+ times per second, even when health hasn't changed!
UpdateHealthBar(player.currentHealth);
}
If you have dozens of UI elements or logic controllers doing this, you are wasting valuable CPU time on operations that perform no actual work 99% of the time. This is "polling," and it is a major performance bottleneck.
The Event-Driven Shift
Instead of asking "Has the health changed?" every frame, we change the architecture to "Tell me when the health changes." By leveraging the Action delegates and observer patterns you've already mastered, we can trigger logic only when an state change actually occurs.
Refactoring the example above becomes a lean, efficient operation:
// Inside your PlayerHealth script
public event Action<int> OnHealthChanged;
public void TakeDamage(int amount) {
currentHealth -= amount;
OnHealthChanged?.Invoke(currentHealth); // Fire event only when damage occurs
}
// Inside your UI script
void OnEnable() {
player.OnHealthChanged += UpdateHealthBar;
}
void OnDisable() {
player.OnHealthChanged -= UpdateHealthBar; // Crucial for memory cleanup
}
private void UpdateHealthBar(int newHealth) {
// This only runs when the health actually changes!
healthSlider.value = newHealth;
}
By removing the Update method entirely from your UI and listener classes, you move from a push-based system (checking everything constantly) to a reactive system (acting only when triggered). This drastically reduces the overhead of your main loop, allowing your CPU to focus on more complex tasks like physics, AI, or rendering.
Key Takeaway: Replace constant Update polling with reactive events to ensure code execution occurs only when state transitions demand it, significantly reducing your frame-by-frame CPU overhead.