Debug
TypeClass (static members)
NamespaceUnityEngine
OutputConsole window, Scene view

Debug

Debug prints messages to the Console and draws lines in the Scene view. It's the quickest way to find out what your code is actually doing.

Static Methods

MethodDescription
Log(object message)Print a normal (white) message.
Log(object message, Object context)Same, and clicking the message highlights context in the Hierarchy. Pass this or gameObject.
LogWarning(object message)Yellow warning.
LogError(object message)Red error. Doesn't stop the game.
LogException(Exception e)Log a caught exception with its stack trace.
DrawLine(start, end, color, duration)Draw a line in the Scene view. duration in seconds (0 = one frame).
DrawRay(start, direction, color, duration)Draw a line from a point in a direction. The length of direction is the length drawn.
Assert(bool condition, message)Logs an error if the condition is false. Removed from release builds.
Break()Pauses the Editor, as if you'd clicked Pause.

Code Samples

Useful logging

// String interpolation ($"...") makes logs readable.
Debug.Log($"{name} took {damage} damage, health now {health}", this);

if (target == null)
{
    Debug.LogWarning($"{name} has no target assigned!", this);
}

Visualize a raycast

Vector3 origin = transform.position;
Vector3 dir = transform.forward * 10f;
bool hit = Physics.Raycast(origin, transform.forward, 10f);
Debug.DrawRay(origin, dir, hit ? Color.green : Color.red);

Gizmos: always-visible helpers in the Scene view

[SerializeField] private float detectRadius = 5f;

void OnDrawGizmosSelected() // only when this object is selected
{
    Gizmos.color = Color.yellow;
    Gizmos.DrawWireSphere(transform.position, detectRadius);
}

What happens at runtime

  1. Debug.Log builds a message, captures a stack trace and sends it to the Console. This is relatively slow, especially with thousands per second.
  2. Logs also run in built games. They go to a log file (Player.log), so leftover logs in Update still cost performance.
  3. Debug.DrawLine/DrawRay only show in the Scene view, or in the Game view when the Gizmos button is on. They do nothing in builds.

Tips

Common Mistakes

See also