During development there will inevitably be times when you encounter behaviour you do not want, so you need to be able to track down the cause of that behaviour before you can fix it. There are two main ways of tracking down bugs which each have advantages in different situations:
Debugger | Logging |
---|---|
The Unity Manual explains how you can use an IDE like Visual Studio as a debugger, allowing you to set "breakpoints" in your script which will pause the execution of the program to step through your code line by line and allow you to view the value of each variable. | The Debug class contains a Log method (and several other variations) which you can use to show a message in the Console window. Logged messages are also saved to a Log File in case you need to debug issues in a runtime build or issues that cause the Unity Editor to crash. |
You can set a breakpoint at any time. | You need to edit your script to call the Log method and let Unity recompile it, meaning you probably also need to exit Play Mode and restart it again. |
You can view any variables on the current object without needing to decide what you want to see beforehand. | You need to decide what to actually log and all messages are kept in a list. This can be bad if you have too many objects all filling up the Console with messages that make it hard to find what you want, but it can also be good if you need to compare the contents of messages from different objects and at different times without knowing what you are looking for beforehand. |
Pauses the game. This makes it very difficult or even impossible to use a debugger for situations like input related issues where you need to be able to play the game properly and then review what actually happened afterwards or network multiplayer where pausing one computer would cause the others to think it disconnected. | Does not pause the game unless you intentionally call |
Also note that Debug.Log
has an optional second parameter to specify the context
of the message so that if you click that message in the Console window it will highlight which object in the Hierarchy the message came from.