Using the Debug Class

Unity has a [code]]czo1OlwiRGVidWdcIjt7WyYqJl19[[/code] class with some really useful functions for speeding up development, testing, and debugging.

You probably already use [code]]czoyOTpcIjxzdHJvbmc+RGVidWcuTG9nKCk8L3N0cm9uZz4gXCI7e1smKiZdfQ==[[/code]to add messages to the Console, such as keeping track of variables or notifying you of certain conditions:

Debug.Log("Player inside trigger area");
Debug.Log("X value: " + x.ToString());

If you don’t use [code]]czoxMTpcIkRlYnVnLkxvZygpXCI7e1smKiZdfQ==[[/code] you should! It will print anything you want into Unity’s console window while running the game in the Editor.

Warnings and Error

The [code]]czo1OlwiRGVidWdcIjt7WyYqJl19[[/code] class also lets you write warnings and errors to the Console. This lets you give yourself valuable feedback when debugging.

Here’s what the different log types look like in the Console window:

logs

Debug .Log, Debug.LogError, and Debug.LogWarning

 

Debug.LogError("This is a debug error message");
Debug.LogWarning("This is a debug warning message");

Pause the Game

Call [code]]czoxMzpcIkRlYnVnLkJyZWFrKClcIjt7WyYqJl19[[/code] to pause your game in the Editor, allowing you to freeze the action at a particular point and look what’s happening:

Debug.Break();

Lines

debug_lines

Debug.DrawLine and Debug.DrawRay

The [code]]czo1OlwiRGVidWdcIjt7WyYqJl19[[/code] class also lets you draw lines inside the Scene view while your game is playing. This is invaluable for working with linecasts and raycasts as it lets you see exactly what is happening in your scene, taking out the guesswork.

Debug lines are especially useful for making sure your vector maths is correct.

[code]]czoxNjpcIkRlYnVnLkRyYXdMaW5lKClcIjt7WyYqJl19[[/code] takes a start point, an end point, and a colour and draws a line (only visible in the Scene window while the game is running):

Debug.DrawLine(transform.position, othertransform.position, Color.magenta);

[code]]czoxNTpcIkRlYnVnLkRyYXdSYXkoKVwiO3tbJiomXX0=[[/code] is similar, but draws a ray from an origin position in a given direction:

Debug.DrawRay(transform.positon, Vector3.up, Color.blue);

Link

Unity documentation for the Debug class: Unity Scripting API: Debug.

One thought on “Using the Debug Class

  1. Pingback: Enemies that Can See! « Unity for All Unity for All

Leave a Reply

Your email address will not be published.