How to Use Debug.Log in Unity for Simple Debugging
Use
Debug.Log in Unity to print messages to the Console window, helping you see values or track code flow during gameplay. Simply call Debug.Log("Your message") inside any script method to output text while the game runs.Syntax
The basic syntax of Debug.Log is simple. You call Debug.Log() and pass a message inside the parentheses. This message can be a string or any variable you want to check.
- Debug.Log(message): Prints the message to the Console.
- message: The text or variable you want to display.
csharp
Debug.Log("Hello, Unity!");Output
Hello, Unity!
Example
This example shows how to use Debug.Log inside the Start() method of a Unity script. When the game starts, it prints a welcome message and a number value to the Console.
csharp
using UnityEngine; public class DebugExample : MonoBehaviour { void Start() { Debug.Log("Game started!"); int score = 10; Debug.Log("Score is: " + score); } }
Output
Game started!
Score is: 10
Common Pitfalls
Some common mistakes when using Debug.Log include:
- Forgetting to add quotes around string messages.
- Trying to log complex objects without converting them to strings.
- Leaving many
Debug.Logcalls in production code, which can slow down the game.
Always remove or comment out debug logs when you finish testing.
csharp
/* Wrong way: missing quotes around string */ // Debug.Log("Hello World"); // This is correct /* Right way: add quotes */ Debug.Log("Hello World");
Quick Reference
Here is a quick summary of useful Debug methods in Unity:
| Method | Description |
|---|---|
| Debug.Log(message) | Prints a normal message to the Console. |
| Debug.LogWarning(message) | Prints a warning message in yellow. |
| Debug.LogError(message) | Prints an error message in red. |
| Debug.LogFormat(format, args) | Prints a formatted message using placeholders. |
Key Takeaways
Use Debug.Log to print messages to Unity's Console for easy debugging.
Always pass a string or convert variables to strings inside Debug.Log.
Remove Debug.Log calls from production code to keep performance smooth.
Use Debug.LogWarning and Debug.LogError for warnings and errors.
Place Debug.Log inside methods like Start or Update to track game events.