In this lesson, you will learn how to use the Debug class to track your game’s internal state and execution flow in real-time without disrupting your player's experience.
Tracking State with Debugging Tools
When your game logic grows complex—such as managing TimeScale or coordinating sequences of Coroutines—it becomes difficult to visualize exactly what is happening under the hood. The Debug class allows you to "print" messages directly to the Console window while the game is running, letting you verify that variables are updating as expected.
Choosing the Right Level
Unity provides three primary methods for logging, each serving a specific purpose:
Debug.Log(message): Use this for general information, such as confirming that a method was triggered or checking the current value of a variable.Debug.LogWarning(message): Use this when something is not quite right, but the game can still function. For example, if a player tries to trigger an input event that isn't currently allowed.Debug.LogError(message): Reserve this for critical issues where logic has failed, such as an object reference missing during a sequence.
Practical Implementation
Consider a scenario where you are monitoring a cooldown timer within a Coroutine. You can log the state to see how it performs across frames:
private IEnumerator CooldownRoutine()
{
float timer = 2.0f;
Debug.Log("Cooldown started with duration: " + timer);
while (timer > 0)
{
timer -= Time.deltaTime;
yield return null;
}
Debug.Log("Cooldown complete!");
}
By adding these logs, you can observe the flow of your Coroutine in the Console without needing to stop or pause the game. You can even use rich text in your strings (like <color=red>) to make specific logs stand out.
Keep it Clean
Be careful not to place Debug.Log inside a high-frequency method like Update or FixedUpdate unless necessary, as it can clutter your Console and impact performance. Only log when a state change occurs or when you need to troubleshoot a specific flow.
Key Takeaway: Use Debug.Log, Warning, and Error as your primary tools to gain visibility into your code’s execution flow and variable states without pausing your gameplay.