Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created January 24, 2024 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AldeRoberge/69554c24ac7c4080af34c2330a1f99ee to your computer and use it in GitHub Desktop.
Save AldeRoberge/69554c24ac7c4080af34c2330a1f99ee to your computer and use it in GitHub Desktop.
Redirects console output (Console.WriteLine) to Unity (Debug.Log)
using System;
using System.IO;
using System.Text;
using UnityEngine;
namespace AGES.Utils.Runtime.Logging
{
/// <summary>
/// Redirects console output (Console.WriteLine) to Unity (Debug.Log)
/// </summary>
public class UnityConsoleRedirect : MonoBehaviour
{
public void Start()
{
Console.SetOut(new UnityTextWriter());
}
private class UnityTextWriter : TextWriter
{
private StringBuilder buffer = new();
public override void Flush()
{
Debug.Log(buffer.ToString());
buffer.Length = 0;
}
public override void Write(string value)
{
buffer.Append(value);
if (value != null)
{
var len = value.Length;
if (len > 0)
{
var lastChar = value[len - 1];
if (lastChar == '\n')
{
Flush();
}
}
}
}
public override void Write(char value)
{
buffer.Append(value);
if (value == '\n')
{
Flush();
}
}
public override void Write(char[] value, int index, int count)
{
Write(new string(value, index, count));
}
public override Encoding Encoding => Encoding.Default;
}
}
}
@AldeRoberge
Copy link
Author

Suggestion of Rich Wepner : I guess you probably want to do the same thing with Console.SetErr as well? 💡

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment