Skip to content

Visual Studio Debugger

pointcache edited this page Jan 18, 2022 · 1 revision

The use of the debugger is mandatory for efficient development. And it is a rather simple tool.

Debugger is built into Visual Studio and if the Visual Studio Tools For Unity is installed, will automatically find Unity Editor and connect to it.

Why:

Debugger allows you to pause code execution at any line, and look into the variables. Debugger allows you to step line by line, so you can analyze where your code is screwing up. Debugger allows you to conditionally stop execution (if, for example some variable is null).

Concepts:

Attaching

Debugger has to "hook" into another process. With unity it is as simple as pressing the 'Attach' button on the top panel. When debugger is attached, unity will display a blue bug icon on the bottom right. Debugger will only work when it is attached. Whether your game is in playmode or not makes no difference for the debugger. It will work as well for editor scripts (custom inspectors etc), stopping the execution of the editor. Possible hotkey is F5, however can differ.

Breakpoint

A line at which the debugger will stop execution, when the code execution reaches it. You can have as many breakpoints as you like. Toggle breakpoint hotkey F9. Remove all breakpoints hotkey Shift + F9.

Observing values

When the execution is paused you can observe the values that are currently accessible in memory. You can hover over the variable and see its contents. You can mark a variable for "watching" which will make it visible in watch window.

MSDN - Watch

Stepping

Once you hit a breakpoint, you can execute code line by line. You can step over, moving one line forward. Default hotkey for that is F10 You can step into a method. By default step over will not go into methods. Default hotkey for step into is F11 You can step out of a method. Default hotkey is Shift + F11

Steps

A common workflow with a debugger: You have a nasty bug with some math, logic, or flow.

  1. Identify the potential line where you should know the values of your variables and put a breakpoint F9
  2. Attach the debugger.
  3. Press Play in unity and reach the code where you have put the breakpoint. (Play the game until you hit it).
  4. Debugger stops execution and you can use all the tools and stepping.
  5. Breakpoint didn't help, remove it F9 and add another one in different place.
  6. Analyze the issue until you found the problem. Restart the play mode, as many times you need to replicate the issue.
  7. Problem solved, remove all breakpoints Shift + F9
  8. Detach the debugger.

FAQ

Q: Why not just use Debug.Log() ? A: Every Log requires code modification and compilation. Log only shows the ToString() of the object, it wont show you every detail, field, inherited values like debugger will. There is also a thing called Tracelog, that does the same.

Clone this wiki locally