Unity: Debugging Infinite Loops

Unity’s Debug.Log has a singularly frustrating interaction with infinite loops: it stops working immediately upon entering the loop. My theory is that Debug.Log is designed only to output to the console at the end of a frame, so if the end of the frame is never reached messages never get written. Whatever the cause, this fundamental debugging tool is useless for working out what code is involved in the loop.

Fortunately, there’s an easy solution: write to a text file. Debug.Log messages won’t show during an infinite loop, but Unity will honor instructions to write to a file as it goes through code endlessly. By writing messages to a file instead of to the console, you can get the information you need.

Outputting text to a file is easy. Copy the following into a new script:

using UnityEngine;
using System.Collections;
using System.IO;

public class FileIO {

/// <summary>
/// Write a string to a file
/// </summary>
/// <param name=”fileName”>File to write to.</param>
/// <param name=”content”>String to write.</param>
/// <param name=”append”>If set to <c>true</c>, append. If set to <c>false<c>, overwrite file.</param>

public static void WriteStringToFile(string fileName, string content, bool append)

StreamWriter sw = new StreamWriter(fileName, append);





You can then use it as follows:

FileIO.WriteStringToFile(“debug.txt”, “Animation begins”, true);

Write as many messages as necessary to determine what’s happening.

A few usage notes:

  • Don’t forget “using System.IO;”
  • Note that this class doesn’t inherit from Monobehaviour, so it can’t be attached as a component. That’s fine; use the syntax above to call the function.
  • By default, the text file appears in the Assets folder.

Here’s hoping this saves someone out there a little time and heartache. 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s