Logging: How-to#


Unity's Debug.Log function will print a message to the Console window (WindowGeneralConsole, CtrlShiftC). Code can pass any object to the log and it will be converted to a string and displayed.

Take extra care ensuring that logs are not disabled using the toggles in the top right of the window.
console toggles

Also be aware when Collapse is enabled in the same toolbar, which will merge identical logs.

String interpolation#

You can use string interpolation to easily insert values into text:

int value = 10;
Debug.Log($"The example value is {value}.");
// Prints: The example value is 10.


When logging it is important to place your log behind any error that can occur, as exceptions will halt execution.

Debug.Log("This will be printed to the Console.");
// <- Line that causes the error
Debug.Log("This will not be printed to the Console.");

The context parameter#

The second parameter, context, is extremely valuable. This object will be pinged in the Hierarchy or Project window when the log is selected in the Console window.

Debug.Log(..., gameObject);

You can use this to check whether there are multiple instances of a script producing a log.

If no object is pinged it generally means it no longer exists in the Hierarchy or Project window. This usually means it was just destroyed.

Null references#

When dealing with null it's access that will throw an exception, so if a long line is causing an NRE it's important to make individual logs for each access, or else the log will also throw an exception and not be printed.

Debug.Log($"Value: {value}");
Debug.Log($"Target: {value.Target}");
Debug.Log($"Image: {value.Target.GetComponent<Image>()}");
Target.GetComponent<Image>().color = Color.white; //<- Line that causes the error

Null values will sometimes print nothing, so note if a log does not print details, it could be a null value.

A much less tedious way of discovering what values are null is to use the debugger, where code execution is halted and values can be inspected directly.

See NullReferenceException for more information.

Extra details#


The ToString implementation for vectors shows very little precision, when logging you should use a format string to show an appropriate number of decimal places. See vector equality for more information.


The print function is only inherited from MonoBehaviour and indirectly calls Debug.Log. It also does not take the context parameter, and so should generally be avoided.

Logs, Warnings, and Errors#

Unity has multiple types of logs:


Log can describe informative or verbose details.


Warning is for non-critical failures, like handled issues or basic misconfiguration.


Error or Exception are for failures that must be addressed, or halt code execution.


You can use the [HideInCallstack] attribute to mark methods to be hidden when Strip Logging Callstack is enabled via the Console window menu. This is useful when creating your own wrappers for logging.