Debug Thy Code! [Unity Essentials]

Why are you only guessing what your script does when it executes?

You can actually experience it!

See how execution runs from one line to the next, and how variables (local, fields) in scope change during execution. You can even step into each method call, provided there is source code available for it.

The magic tool for this is the debugger:

This screenshot shows a breakpoint - this is where execution stops and pops up your IDE to allow you to inspect the current state of the program.

If the breakpoint never hits, it also tells you something. Barring any debugger issues it means the code never got to that point.

The officially supported IDEs have a built-in debugger, which means either Visual Studio Community or JetBrains Rider. VS Code has one too but only with the proper plugins, as per the usual.

To use the debugger requires clicking the “attach” button or menu item, and then continue playing, or enter Play Mode, or just debug an editor script. For more details refer to the Unity manual and your IDE’s manual.

It is absolutely mandatory to learn to use the debugger as early as possible in your journey to writing code. Not only will it save you time, it also provides valuable insights into how your code is actually working.

Unexpected Benefits

You’ll be encouraged to write more readable, maintainable code. :wink:

4 Likes

I’ll suggest a convention for debug messages as well. People write all sorts of one-up “ran this” and “before calculation” type messages.

Consider a pattern Debug.Log(“ExampleScript.Start”);

You know the class and method and can easily tack on more data as needed.