Skip to content
ToanLB
Go back

Inspecting Runtime State in Unity: Moving Beyond [SerializeField] and Debug.Log

~8 min read
Inspecting Runtime State in Unity: Moving Beyond [SerializeField] and Debug.Log

During everyday gameplay programming in Unity, almost every developer adopts a familiar habit: Upon writing a transient runtime state variable such as _currentHealth, _currentSpeed, or _comboCounter, we reflexively slap [SerializeField] private right in front of it. The primary motivation is not providing game designers with tunable variables, but simply peeking at the Inspector window in Play Mode to verify that the value increments or decrements as expected.

When production teams begin tightening architecture and enforcing the removal of unnecessary serialization attributes to prevent prefab clutter, a very practical question surfaces. This topic stems from an insightful question raised by community reader @Huy Phạm under our video deep dive into Unity Serialization:

“If you don’t use [SerializeField] to debug runtime, do you just use Debug.Log?”

This is a completely natural reaction. When developers need to observe runtime states but are discouraged from using [SerializeField], the next instinctive tool that comes to mind is Debug.Log. However, treating [SerializeField] and Debug.Log as the only two debugging alternatives inadvertently traps teams between two technical antipatterns: one silently pollutes version-controlled asset files, while the other generates continuous heap allocations that degrade frame rates.


Dissecting the Two Traps: When Observation Tools Become Technical Debt

Before exploring clean alternatives, it is crucial to understand why these intuitive habits introduce serious issues in commercial projects:

1. The True Nature of [SerializeField] Is Not Debugging

Developers often perceive [SerializeField] as an Inspector visual toggle. Under the hood, however, this attribute serves an entirely different purpose: Registering a C# field with the native Unity Serialization Engine.

When decorating _currentHealth with [SerializeField]:

2. The GC Allocation Pitfall of Spamming Debug.Log in Game Loops

When stripping [SerializeField], the immediate alternative is often sprinkling Debug.Log calls inside Update() or FixedUpdate():

public class DebugLogAntiPattern : MonoBehaviour
{
    private int _comboCount = 5;
    private float _currentSpeed = 12.5f;

    void Update()
    {
        // Antipattern: Continuous heap allocation every frame due to string concatenation and boxing
        Debug.Log("Combo: " + _comboCount + " | Toc do: " + _currentSpeed);
    }
}

This seemingly harmless log statement triggers significant garbage collection pressure for three reasons:

  1. String Concatenation: Every frame allocates a brand-new string object on the Managed Heap, forcing the Garbage Collector (GC) to run frequently and induce frame drops.
  2. Boxing Overhead: Passing value types such as int or float into string formatting operations forces the C# runtime to box stack values into heap objects.
  3. Formatting and StackTrace Costs: Even if console display is muted, Debug.Log still incurs CPU time constructing the string and capturing the stack frame. If shipped to mobile release builds, these logs drain battery and cause device thermal throttling.
flowchart LR
    A["Runtime State Observation Need"] --> B{"Choose Approach"}
    B -->|"Inspect values directly"| C["Inspector Debug Mode (Native)"]
    B -->|"Observe specific C# properties"| D["Custom ReadOnly Drawer"]
    B -->|"Real-time on-device metrics"| E["In-Game Debug Overlay (0 GC)"]
    B -->|"Conditional instrumentation"| F["Conditional Logger [Conditional]"]
    
    C --> G["No YAML Serialization"]
    D --> G
    E --> H["Zero GC Alloc in Update"]
    F --> H

4 Professional Diagnostics Solutions for Unity Developers

To observe runtime variables accurately without dirtying prefab assets or generating garbage collections, developers can leverage four production-grade approaches:

Solution 1: Inspector Debug Mode (Built-in)

Unity includes a powerful built-in diagnostic view that is frequently overlooked:

Instantly, all private fields across your scripts appear in the Inspector without requiring a single [SerializeField] attribute. You can monitor and adjust values during Play Mode without altering the prefab’s serialized YAML footprint in Normal mode.

How to enable Inspector Debug Mode in Unity

Solution 2: The Truth About [ReadOnly] and Custom Property Drawers

A pervasive misconception among developers is believing that UnityEngine contains a built-in [ReadOnly] attribute.

In reality, Unity provides no native [ReadOnly] attribute whatsoever. Whenever you see [ReadOnly] in commercial codebases, it originates from one of two sources:

  1. Third-party editor toolkits such as Odin Inspector ([ReadOnly], [ShowInInspector]), NaughtyAttributes ([ReadOnly]), or MyBox.
  2. A custom PropertyAttribute and PropertyDrawer written by the studio engineering team.

If your project does not use Odin Inspector, you can easily implement a clean [ReadOnly] attribute using standard Unity APIs. The core mechanism uses EditorGUI.BeginDisabledGroup(true) to render fields in a non-editable state:

using UnityEngine;

// Placed in Runtime Scripts directory
public class ReadOnlyAttribute : UnityEngine.PropertyAttribute { }

With the corresponding drawer placed in an Editor/ folder:

#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // Disable input to render read-only runtime value
        EditorGUI.BeginDisabledGroup(true);
        EditorGUI.PropertyField(position, property, label, true);
        EditorGUI.EndDisabledGroup();
    }
}
#endif

This solution keeps values clearly visible in the Inspector without permitting accidental manual modifications in Edit Mode.

Solution 3: In-Game Diagnostics Overlay (Zero GC)

When testing builds on physical mobile devices or standalone consoles, the Unity Editor Inspector is unavailable. In these scenarios, constructing an in-game HUD overlay via UI Toolkit or IMGUI is the optimal path.

By reusing string buffers (StringBuilder or preallocated text buffers), you can render dozens of real-time metrics (FPS, memory usage, state machine transitions) with 0 bytes of GC allocation.

Solution 4: Conditional Logging with [System.Diagnostics.Conditional]

When console logging is necessary, wrap log calls inside helper methods decorated with [Conditional("DEVELOPMENT_BUILD")] or [Conditional("UNITY_EDITOR")].

The C# compiler automatically strips these method invocations from release builds. You never have to manually strip diagnostic logs prior to store submission.


Production C# Implementation: Runtime Diagnostics Tracker

The following implementation provides a decoupled RuntimeDiagnosticsTracker to observe gameplay metrics without serialization dependencies, paired with a conditional SafeLogger verified via automated NUnit tests.

Declaring Diagnostics Tracker Independent of Serialization

The RuntimeDiagnosticsTracker class acts as an in-memory registry of diagnostic key-value getters, completely isolated from scene serialization lifecycles.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using NUnit.Framework;

// In-memory runtime diagnostics service isolated from serialization
public class RuntimeDiagnosticsTracker
{
    private readonly Dictionary<string, Func<string>> _monitoredMetrics = new Dictionary<string, Func<string>>();
    private readonly StringBuilder _cachedBuffer = new StringBuilder(256);

    public void RegisterMetric(string metricName, Func<string> valueGetter)
    {
        if (string.IsNullOrWhiteSpace(metricName)) throw new ArgumentNullException(nameof(metricName));
        if (valueGetter == null) throw new ArgumentNullException(nameof(valueGetter));

        _monitoredMetrics[metricName] = valueGetter;
    }

    public void UnregisterMetric(string metricName)
    {
        if (!string.IsNullOrWhiteSpace(metricName))
        {
            _monitoredMetrics.Remove(metricName);
        }
    }

    public string BuildDiagnosticsSnapshot()
    {
        _cachedBuffer.Clear();
        foreach (var pair in _monitoredMetrics)
        {
            _cachedBuffer.Append(pair.Key);
            _cachedBuffer.Append(": ");
            _cachedBuffer.Append(pair.Value.Invoke());
            _cachedBuffer.AppendLine();
        }
        return _cachedBuffer.ToString().TrimEnd();
    }
}

// Conditional logging wrapper stripped in release builds
public static class SafeLogger
{
    [Conditional("DEBUG")]
    [Conditional("UNITY_EDITOR")]
    public static void LogDebug(string message, ref string outputLogForTest)
    {
        outputLogForTest = "[DEBUG] " + message;
    }
}

Implementing Gameplay State Binding

The HeroCombatState class encapsulates internal state as private fields without [SerializeField], binding getters to the diagnostics tracker.

public class HeroCombatState
{
    // Pure runtime state without YAML serialization
    private int _health = 100;
    private int _comboCount = 0;

    public int Health => _health;
    public int ComboCount => _comboCount;

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

    public void PerformHit()
    {
        _comboCount++;
    }

    public void BindToDiagnostics(RuntimeDiagnosticsTracker tracker)
    {
        tracker.RegisterMetric("Hero_Health", () => _health.ToString());
        tracker.RegisterMetric("Hero_Combo", () => _comboCount.ToString());
    }
}

Automated NUnit Regression Test Suite

The test suite validates dynamic metric tracking, getter evaluation, and conditional logging.

[TestFixture]
public class RuntimeDiagnosticsTests
{
    private RuntimeDiagnosticsTracker _tracker;
    private HeroCombatState _hero;

    [SetUp]
    public void SetUp()
    {
        _tracker = new RuntimeDiagnosticsTracker();
        _hero = new HeroCombatState();
        _hero.BindToDiagnostics(_tracker);
    }

    [Test]
    public void DiagnosticsTracker_ReflectsHeroStateChanges_WithoutSerialization()
    {
        // Baseline snapshot before combat
        string initialSnapshot = _tracker.BuildDiagnosticsSnapshot();
        Assert.IsTrue(initialSnapshot.Contains("Hero_Health: 100"));
        Assert.IsTrue(initialSnapshot.Contains("Hero_Combo: 0"));

        // Simulate combat actions
        _hero.TakeDamage(35);
        _hero.PerformHit();
        _hero.PerformHit();

        // Snapshot immediately reflects updated getter values
        string updatedSnapshot = _tracker.BuildDiagnosticsSnapshot();
        Assert.IsTrue(updatedSnapshot.Contains("Hero_Health: 65"));
        Assert.IsTrue(updatedSnapshot.Contains("Hero_Combo: 2"));
    }

    [Test]
    public void UnregisterMetric_RemovesMetricFromSnapshot()
    {
        _tracker.UnregisterMetric("Hero_Combo");
        string snapshot = _tracker.BuildDiagnosticsSnapshot();

        Assert.IsTrue(snapshot.Contains("Hero_Health: 100"));
        Assert.IsFalse(snapshot.Contains("Hero_Combo"));
    }

    [Test]
    public void SafeLogger_SetsOutputUnderDebugConditions()
    {
        string logResult = string.Empty;
        SafeLogger.LogDebug("Physics engine initialized.", ref logResult);

        Assert.AreEqual("[DEBUG] Physics engine initialized.", logResult);
    }
}

Comparative Trade-off Analysis

MetricUsing [SerializeField] to ViewUsing Debug.Log in LoopsInspector Debug ModeIn-Game Diagnostics Overlay
Design PurposePersistent asset serialization.Instant ephemeral event logging.Inspecting private runtime state.Real-time on-device telemetry.
Asset ImpactSevere: Dirties YAML, causes Git conflicts.Zero impact on asset files.Pristine: 0% asset modifications.Pristine: 0% asset modifications.
GC Allocations0 bytes GC Alloc.High: continuous string allocations and boxing.0 bytes GC Alloc.Negligible (0 bytes when buffered).
Mobile ViabilityCompletely useless in standalone builds.Requires Logcat or terminal debugging.Completely useless in standalone builds.Outstanding: visible directly on test devices.
Recommended UseTunable designer configuration data.Discrete error and event handlers.Rapid desktop editor verification.Production projects and playtesting.

Production Takeaways

The question raised by @Huy Phạm serves as an important reminder to respect the intended boundaries of Unity’s toolset:

  1. Avoid turning transient states into persistent data: [SerializeField] is designed for engine persistence. Do not use it as a makeshift visualizer for temporary numbers.
  2. Embrace Inspector Debug Mode: Switch your Inspector to Debug mode to inspect private state without altering code.
  3. Know the reality of [ReadOnly]: Remember that Unity has no native [ReadOnly] attribute; implement a simple PropertyDrawer or leverage tools like Odin Inspector.
  4. Protect the game loop from GC Allocations: Keep Debug.Log out of Update(). When real-time monitoring is required, rely on buffered diagnostics overlays or specialized profilers.

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.