Skip to content
ToanLB
Go back

Polling UI in Update(): When Quick Fixes Turn into Technical Debt

~14 min read
Polling UI in Update(): When Quick Fixes Turn into Technical Debt

During crunch hours before an internal playtest build or a milestone demo, many game developers encounter a familiar headache: character combat logic updates rapidly under the hood, but the health bar or score label on the HUD lags behind or fails to sync reliably.

Under tight deadlines, the quickest and most tempting band-aid is often throwing a temporary component straight into the Update() method:

using UnityEngine;

public class EmergencyHpBar : MonoBehaviour
{
    public int currentHp = 100;
    public int maxHp = 100;
    public string displayedText;

    private void Update()
    {
        // Polling and string formatting continuously 60 times a second
        displayedText = $"{currentHp}/{maxHp}";
    }
}

Pressing Play confirms it works immediately: the health bar responds instantly to incoming attacks, QA signs off, and the build ships on time. However, as the project expands, adding dozens of complex screens and persistent status effects, this seemingly harmless shortcut starts demanding repayment with heavy interest.

This deep dive examines the true cost of polling UI inside Update(), spanning low-level runtime engine performance to long-term architectural stability, accompanied by a step-by-step refactoring roadmap toward C# Events and the Model - View - Presenter (MVP) pattern.


1. Deconstructing the Real Cost of Frame-by-Frame UI Polling

At first glance, updating a text string in Update() appears trivial given modern CPU clock speeds. Within the Unity Engine, however, a simple UI assignment triggers a cascading series of operations across both the native C++ engine and the managed garbage-collected heap.

1.1. The Hidden Heap Garbage from String Concatenation and Boxing

Strings in C# are immutable reference types. Calling player.CurrentHp.ToString() alone does not induce boxing because Int32 directly overrides ValueType.ToString().

However, using string interpolation $"{player.CurrentHp}/{player.MaxHp}" or calling string.Format("{0}/{1}", ...) causes the C# compiler to lower the syntax into string.Format(string, object, object). At this point, both integer value-types are boxed into two heap objects, along with the newly created string:

1.2. Canvas Rebuild Pressures and the Limits of Equality Guards

In Unity UI (uGUI), each Canvas acts as a batched rendering unit responsible for combining geometric elements into combined draw calls for the GPU.

Both legacy Text and TextMeshProUGUI feature an internal equality guard: if the incoming string matches the currently displayed text (m_text == value), the setter returns immediately without marking the mesh as dirty. However, polling inside Update() remains harmful for two primary reasons:

  1. Wasted CPU Cycles: Even when the Canvas avoids a rebuild because the string hasn’t changed, the CPU still expends cycles formatting strings, boxing two integers, and executing character-by-character comparisons 60 times a second for every active UI element.
  2. Full Canvas Rebuilds on State Mutations: As soon as health values actually change (even by 1 HP or during smooth bar lerping), the setter invokes SetVerticesDirty(). At the end of the frame, the containing Canvas triggers a complete Canvas Rebuild, recalculating vertices, UVs, and vertex colors for all UI elements sharing that Canvas.

A crucial distinction to remember: Architectural patterns (such as Event-Driven or MVP) eliminate Canvas Rebuilds when data is idle. When values change dynamically, developers must pair architecture with Sub-Canvas Partitioning: isolating dynamic elements (such as frequently moving health bars) onto dedicated Sub-Canvases separate from static HUD elements.

1.3. The Architectural Threat: Views Knowing Too Much About Data

Beyond runtime performance, the architectural coupling poses an even larger maintenance liability:

flowchart LR
    subgraph BadArchitecture["Tight Coupling Anti-Pattern"]
        UI["PlayerHealthView (MonoBehaviour)"]
        Data["PlayerStats (God Class / Singleton)"]
    end

    UI -->|"Reads directly in Update()"| Data
    UI -.->|"Calculates: if (hp < 20) -> Color Red"| UI

When a View component handles both visual rendering and queries PlayerStats directly while calculating domain display rules (such as “if health drops below 20%, turn the text red”), it breaches the Single Responsibility Principle. The visual layer becomes tightly coupled with game logic:


2. The Prototype Approach: Convenient but Tightly Coupled

To understand the hidden costs of UI polling, consider a combat HUD in a mobile third-person shooter or Action RPG targeting a sustained 60 FPS. The screen displays the player’s vital stats (CurrentHp/MaxHp), the ongoing match score, and must transition into a high-visibility danger state (flashing red) as soon as health dips below a 20% critical threshold.

On resource-constrained mobile hardware, string concatenation such as $"{player.CurrentHp}/{player.MaxHp}" evaluated 60 times per second inside Update() generates relentless heap allocations. This churn periodically awakens the garbage collector, inducing stutter during intense firefights. Worse still, constantly mutating the text field marks the Canvas dirty every frame, forcing costly Canvas mesh rebuilds on the main thread even when health hasn’t budged. Compounding the issue, embedding the threshold formatting directly inside MonoBehaviour scripts leaves critical presentation logic completely untestable without instantiating scene graphics.

Initial Prototype: Continuous Polling in Update

using System;
using UnityEngine;

// Domain model holding player data
public class PlayerModel
{
    public int CurrentHp { get; set; } = 100;
    public int MaxHp { get; set; } = 100;
    public int Score { get; set; } = 0;

    public void TakeDamage(int damage)
    {
        CurrentHp = Math.Max(0, CurrentHp - damage);
    }
}

// Visual component attached to a UI GameObject, polling every frame
public class LegacyPlayerView : MonoBehaviour
{
    public PlayerModel player;

    // Simulated Inspector output fields
    public string displayedText;
    public string displayedColor;

    private void Update()
    {
        if (player == null) return;

        // Issue 1: Allocates a new string every frame even when values remain unchanged
        displayedText = $"{player.CurrentHp}/{player.MaxHp}";

        // Issue 2: Presentation logic is hardcoded directly inside the View
        if (player.CurrentHp <= player.MaxHp * 0.2f)
        {
            displayedColor = "RED_WARNING";
        }
        else
        {
            displayedColor = "WHITE_NORMAL";
        }
    }
}

In this implementation, LegacyPlayerView directly couples to PlayerModel, continuously executes floating-point comparisons every frame, and cannot be executed inside automated test harnesses without instantiating Unity Scene GameObjects.


3. Level 1: Moving to Event-Driven Architecture with Pure C# Events

The first architectural evolution replaces continuous Pull (polling every frame) with an explicit Push (notifying subscribers upon mutation) model. When the player’s health actually changes, our domain model (EventDrivenPlayerModel) fires an event, allowing the listener view (EventDrivenHealthView) to respond once.

flowchart LR
    subgraph EventDriven["Push Mechanism via Pure C# Events"]
        Model["EventDrivenPlayerModel"]
        UI["EventDrivenHealthView"]
    end

    Model -->|"Fires OnHpChanged(cur, max)"| UI
    UI -.->|"Updates only when event arrives"| UI

Implementing the Event-Driven Model and View

using System;
using UnityEngine;

// 1. Pure C# model firing events only when values actually change
public class EventDrivenPlayerModel
{
    public int CurrentHp { get; private set; }
    public int MaxHp { get; private set; }

    // Pure C# event broadcasting current and maximum health values
    public event Action<int, int> OnHpChanged;

    public EventDrivenPlayerModel(int maxHp)
    {
        MaxHp = Math.Max(1, maxHp);
        CurrentHp = MaxHp;
    }

    public void TakeDamage(int damage)
    {
        if (damage <= 0) return;
        int newHp = Math.Max(0, CurrentHp - damage);
        if (newHp != CurrentHp)
        {
            CurrentHp = newHp;
            OnHpChanged?.Invoke(CurrentHp, MaxHp);
        }
    }
}

// 2. View component strictly updates on notifications
public class EventDrivenHealthView : MonoBehaviour
{
    private EventDrivenPlayerModel _model;
    public string DisplayedText { get; private set; }

    public void Initialize(EventDrivenPlayerModel model)
    {
        // Unsubscribe from previous model to prevent dangling listeners
        if (_model != null)
        {
            _model.OnHpChanged -= HandleHpChanged;
        }

        _model = model ?? throw new ArgumentNullException(nameof(model));
        _model.OnHpChanged += HandleHpChanged;

        // Synchronize initial state
        HandleHpChanged(_model.CurrentHp, _model.MaxHp);
    }

    private void HandleHpChanged(int currentHp, int maxHp)
    {
        DisplayedText = $"{currentHp}/{maxHp}";
    }

    // Always unsubscribe on destruction to eliminate memory leaks
    private void OnDestroy()
    {
        if (_model != null)
        {
            _model.OnHpChanged -= HandleHpChanged;
        }
    }
}

Unit Testing Level 1 Logic

The event notification flow of EventDrivenPlayerModel runs cleanly in memory without any engine dependencies:

using NUnit.Framework;

[TestFixture]
public class EventDrivenPlayerModelTests
{
    [Test]
    public void TakeDamage_ValidDamage_FiresEventWithUpdatedHp()
    {
        var model = new EventDrivenPlayerModel(maxHp: 100);
        int capturedCurrent = -1;
        int capturedMax = -1;
        int eventCallCount = 0;

        model.OnHpChanged += (cur, max) =>
        {
            capturedCurrent = cur;
            capturedMax = max;
            eventCallCount++;
        };

        model.TakeDamage(damage: 30);

        Assert.AreEqual(70, capturedCurrent, "capturedCurrent");
        Assert.AreEqual(100, capturedMax, "capturedMax");
        Assert.AreEqual(1, eventCallCount, "eventCallCount");
    }

    [Test]
    public void TakeDamage_ZeroOrNegativeDamage_DoesNotFireEvent()
    {
        var model = new EventDrivenPlayerModel(maxHp: 100);
        int eventCallCount = 0;
        model.OnHpChanged += (cur, max) => eventCallCount++;

        model.TakeDamage(damage: 0);
        model.TakeDamage(damage: -10);

        Assert.AreEqual(0, eventCallCount, "eventCallCount");
        Assert.AreEqual(100, model.CurrentHp, "model.CurrentHp");
    }
}

The Lifecycle Pitfall in Level 1

In C#, when executing publisher.OnEvent += subscriber.Handler, the Publisher retains a strong reference to the Subscriber inside its internal _invocationList.

If PlayerModel is a long-lived object (such as a session-level manager or ScriptableObject) while EventDrivenHealthView resides on a UI screen destroyed during scene transitions without unsubscribing in OnDestroy():


4. Level 2: Clean Boundaries with Model - View - Presenter (MVP)

While pure events resolve the polling overhead, real-world UI requirements quickly introduce presentation logic:

Placing these formatting rules and conditions inside the View bloats visual scripts and prevents automated testing. This is where the Model - View - Presenter (MVP) pattern provides architectural leverage through four explicit classes in our sample: PlayerStatsModel (Model), PlayerHealthPresenter (Presenter), IPlayerHealthView (View interface), and UnityHealthView (MonoBehaviour implementation):

flowchart TD
    subgraph MVPPattern["MVP Architectural Separation"]
        Model["PlayerStatsModel (Pure Data)"]
        Presenter["PlayerHealthPresenter (Pure C# - Presentation Logic)"]
        View["IPlayerHealthView (Thin Interface)"]
        UnityUI["UnityHealthView (MonoBehaviour Rendering)"]
    end

    Model -->|"Data mutation events"| Presenter
    Presenter -->|"Calculates colors, formats strings, invokes"| View
    UnityUI -.->|"implements"| View

Core Responsibilities in MVP

  1. Model: Encapsulates business data and state transitions (health, armor, damage calculations).
  2. View (IPlayerHealthView): A lightweight C# interface defining rendering primitives (SetHealthRatio, SetHealthText, SetCriticalWarning). The View contains zero branching or computational logic.
  3. Presenter: A pure C# class that does not inherit from MonoBehaviour. It observes the Model, computes presentation rules (percentages, threshold warnings, string formats), and commands the View to render.

Implementing the MVP Structure

using System;

// 1. Thin View Interface independent of UnityEngine UI
public interface IPlayerHealthView
{
    void SetHealthRatio(float ratio);
    void SetHealthText(string text);
    void SetCriticalWarning(bool isCritical);
}

// 2. Pure domain model holding player statistics
public class PlayerStatsModel
{
    public int CurrentHp { get; private set; }
    public int MaxHp { get; private set; }
    public event Action<int, int> OnHpChanged;

    public PlayerStatsModel(int maxHp)
    {
        MaxHp = Math.Max(1, maxHp);
        CurrentHp = MaxHp;
    }

    public void ApplyDamage(int damage)
    {
        if (damage <= 0) return;
        int nextHp = Math.Max(0, CurrentHp - damage);
        if (nextHp != CurrentHp)
        {
            CurrentHp = nextHp;
            OnHpChanged?.Invoke(CurrentHp, MaxHp);
        }
    }
}

// 3. Pure C# Presenter: Decoupled from Unity Engine and 100% testable
public class PlayerHealthPresenter : IDisposable
{
    private readonly PlayerStatsModel _model;
    private readonly IPlayerHealthView _view;

    // Critical health threshold ratio (below 20%)
    private const float CriticalThreshold = 0.2f;

    public PlayerHealthPresenter(PlayerStatsModel model, IPlayerHealthView view)
    {
        _model = model ?? throw new ArgumentNullException(nameof(model));
        _view = view ?? throw new ArgumentNullException(nameof(view));

        _model.OnHpChanged += HandleHpChanged;
        RefreshView();
    }

    private void HandleHpChanged(int currentHp, int maxHp)
    {
        RefreshView();
    }

    public void RefreshView()
    {
        float ratio = (float)_model.CurrentHp / _model.MaxHp;
        string text = $"{_model.CurrentHp}/{_model.MaxHp}";
        bool isCritical = ratio <= CriticalThreshold;

        _view.SetHealthRatio(ratio);
        _view.SetHealthText(text);
        _view.SetCriticalWarning(isCritical);
    }

    public void Dispose()
    {
        _model.OnHpChanged -= HandleHpChanged;
    }
}

// 4. Concrete View attached to a UI GameObject (MonoBehaviour)
public class UnityHealthView : MonoBehaviour, IPlayerHealthView
{
    // Simulated UI component serialized references
    public float currentFillRatio;
    public string displayedText;
    public string displayedColor;

    private PlayerHealthPresenter _presenter;

    public void Initialize(PlayerStatsModel model)
    {
        // Instantiate Presenter and bind View
        _presenter = new PlayerHealthPresenter(model, this);
    }

    public void SetHealthRatio(float ratio) => currentFillRatio = ratio;
    public void SetHealthText(string text) => displayedText = text;
    public void SetCriticalWarning(bool isCritical) =>
        displayedColor = isCritical ? "RED_WARNING" : "WHITE_NORMAL";

    // Releasing the Presenter is mandatory to prevent event memory leaks from Model
    private void OnDestroy()
    {
        _presenter?.Dispose();
    }
}

Comprehensive Unit Testing with a Fake View

Because IPlayerHealthView and PlayerHealthPresenter are pure C# constructs, complete presentation logic can be verified in milliseconds:

using NUnit.Framework;

[TestFixture]
public class PlayerHealthPresenterTests
{
    // In-memory test double capturing Presenter outputs
    private class FakeHealthView : IPlayerHealthView
    {
        public float LastRatio { get; private set; }
        public string LastText { get; private set; }
        public bool LastCritical { get; private set; }
        public int UpdateCount { get; private set; }

        public void SetHealthRatio(float ratio)
        {
            LastRatio = ratio;
            UpdateCount++;
        }

        public void SetHealthText(string text) => LastText = text;
        public void SetCriticalWarning(bool isCritical) => LastCritical = isCritical;
    }

    [Test]
    public void Presenter_WhenInitialized_UpdatesViewWithFullHealthAndNoWarning()
    {
        var model = new PlayerStatsModel(maxHp: 100);
        var view = new FakeHealthView();

        using (var presenter = new PlayerHealthPresenter(model, view))
        {
            Assert.AreEqual(1.0f, view.LastRatio, 0.0001f, "view.LastRatio");
            Assert.AreEqual("100/100", view.LastText, "view.LastText");
            Assert.AreEqual(false, view.LastCritical, "view.LastCritical");
        }
    }

    [Test]
    public void ApplyDamage_DroppingBelowThreshold_TriggersCriticalWarning()
    {
        var model = new PlayerStatsModel(maxHp: 100);
        var view = new FakeHealthView();

        using (var presenter = new PlayerHealthPresenter(model, view))
        {
            // Drop health from 100 to 15 (15% <= 20% critical threshold)
            model.ApplyDamage(damage: 85);

            Assert.AreEqual(0.15f, view.LastRatio, 0.0001f, "view.LastRatio");
            Assert.AreEqual("15/100", view.LastText, "view.LastText");
            Assert.AreEqual(true, view.LastCritical, "view.LastCritical");
        }
    }

    [Test]
    public void ApplyDamage_OverkillDamage_ClampsRatioToZero()
    {
        var model = new PlayerStatsModel(maxHp: 50);
        var view = new FakeHealthView();

        using (var presenter = new PlayerHealthPresenter(model, view))
        {
            model.ApplyDamage(damage: 999);

            Assert.AreEqual(0.0f, view.LastRatio, 0.0001f, "view.LastRatio");
            Assert.AreEqual("0/50", view.LastText, "view.LastText");
            Assert.AreEqual(true, view.LastCritical, "view.LastCritical");
        }
    }

    [Test]
    public void Presenter_WhenDisposed_StopsListeningToModelEvents()
    {
        var model = new PlayerStatsModel(maxHp: 100);
        var view = new FakeHealthView();
        var presenter = new PlayerHealthPresenter(model, view);

        // Dispose Presenter
        presenter.Dispose();
        int callCountBefore = view.UpdateCount;

        // Trigger damage after disposal
        model.ApplyDamage(damage: 30);

        Assert.AreEqual(callCountBefore, view.UpdateCount, "view.UpdateCount");
    }
}

5. Level 3: Reactive Mindset and Data Binding at Scale

When a game scales to dozens of synchronized interfaces (Inventory, Shop, Equipment, Guilds, Leaderboards), manually orchestrating boilerplate events (OnHpChanged, OnGoldChanged, OnLevelChanged) across hundreds of presenters can become tedious.

At this inflection point, large-scale engineering teams often adopt Reactive Extensions (UniRx or R3) or lightweight BindableProperty<T> patterns to enable declarative data binding.

using System;
using System.Collections.Generic;

// Lightweight pure C# bindable container demonstrating reactive synchronization
public class BindableProperty<T>
{
    private T _value;
    private readonly List<Action<T>> _listeners = new List<Action<T>>();

    public T Value
    {
        get => _value;
        set
        {
            if (!EqualityComparer<T>.Default.Equals(_value, value))
            {
                _value = value;
                NotifyListeners();
            }
        }
    }

    public BindableProperty(T initialValue = default(T))
    {
        _value = initialValue;
    }

    public IDisposable Subscribe(Action<T> onValueChanged)
    {
        if (onValueChanged == null) throw new ArgumentNullException(nameof(onValueChanged));
        _listeners.Add(onValueChanged);
        onValueChanged(_value); // Emit initial value immediately upon binding

        return new Subscription(() => _listeners.Remove(onValueChanged));
    }

    private void NotifyListeners()
    {
        for (int i = _listeners.Count - 1; i >= 0; i--)
        {
            _listeners[i]?.Invoke(_value);
        }
    }

    private class Subscription : IDisposable
    {
        private Action _unsubscribeAction;
        public Subscription(Action unsubscribeAction) => _unsubscribeAction = unsubscribeAction;
        public void Dispose()
        {
            _unsubscribeAction?.Invoke();
            _unsubscribeAction = null;
        }
    }
}

Under this structure, Models declare observable properties such as public readonly BindableProperty<int> CurrentHp = new(100);. Views or Presenters simply invoke CurrentHp.Subscribe(hp => text.text = hp.ToString()). Releasing subscriptions via standard IDisposable cleanups ensures lifecycle management remains consistent across screens.


6. Trade-Off Evaluation Across Approaches

Architectural choices depend entirely on scope, delivery timelines, and team familiarity:

Comparison MetricPolling in Update()Pure C# EventsMVP Pattern (Presenter)Reactive Data Binding (R3/UniRx)
Prototyping SpeedFastest (single line of code)Fast (minutes to declare events)Moderate (requires interfaces)Slower initial setup curve
CPU & Canvas LoadVery high (runs every 60 FPS)Very low (runs only on mutation)Very low (paints only on change)Very low (optimized streams)
Garbage Collection (GC)Continuous string allocationsZero-alloc when avoiding boxingString allocated only upon state changes (eliminates 99% of garbage)Delegate allocations if capturing closure
Unit TestabilityVirtually impossibleDomain model testable100% presentation logic testableEntire reactive pipeline testable
Memory Leak RisksNone from delegatesHigh if forgetting to unsubscribe -=Managed explicitly in Dispose()Managed via CompositeDisposable
Codebase ComplexitySimplest at the beginningLightweight and readableHigher file and class countRequires strong team reactive expertise

7. Practical Engineering Takeaways

  1. Do not demonize Update() unconditionally: During 48-hour game jams or exploratory prototypes where game designers evaluate mechanic feel, placing a temporary line inside Update() is entirely pragmatic. The key is recognizing it as deliberate technical debt that must be paid down before feature expansion begins.
  2. Start with pure C# events before adopting heavy frameworks: Avoid importing complex reactive frameworks or dependency injection containers when a game has only five UI screens. Pure event Action<T> paired with clean unsubscription in OnDestroy() resolves 80% of performance issues with negligible overhead.
  3. Introduce MVP when presentation logic grows: When a View begins accumulating multiple if/else checks, formatting numbers, or querying scene singletons, that is the clearest architectural signal to introduce an intermediary Presenter.
  4. Always measure with the Unity Profiler: Before assuming UI performance is CPU-bound, profile with Deep Profiling enabled. Identify whether frame spikes stem from C# execution time, Canvas Rebuild mesh generation, or frequent Garbage Collector invocations. Engineering decisions based on telemetry consistently outperform speculative optimizations.

Share this post:
Lương Bảo Toàn

Luong Bao Toan

I work in HMI Automotive and Game development, sharing knowledge, hands-on experience, and stories I find interesting throughout my journey.

Did this article bring you value?

If this article helped your work, or you simply enjoyed it and want to support me, you can

Buy me a coffee

Related Articles

Comments & Discussions

Powered by Giscus

Get New Posts via Email

Subscribe to stay updated and never miss new posts from me.

* No spam. You can unsubscribe at any time with a single click.