Last active
November 15, 2024 20:53
-
-
Save AldeRoberge/69554c24ac7c4080af34c2330a1f99ee to your computer and use it in GitHub Desktop.
Redirects console output (Console.WriteLine) to Unity (Debug.Log). Keep in mind that this will probably add some internal logging of Unity to your Editor console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Text; | |
using UnityEngine; | |
namespace Generator.Scripts.Runtime.Utilities.Logging | |
{ | |
/// <summary> | |
/// Redirects console output (Console.WriteLine) to Unity (Debug.Log) | |
/// </summary> | |
public class UnityConsoleRedirect : MonoBehaviour | |
{ | |
public void Start() | |
{ | |
Console.SetOut(new UnityTextWriter(false)); | |
Console.SetError(new UnityTextWriter(true)); | |
} | |
private class UnityTextWriter : TextWriter | |
{ | |
private readonly StringBuilder _buffer = new(); | |
private readonly bool _isError; | |
public UnityTextWriter(bool isError) | |
{ | |
_isError = isError; | |
} | |
public override void Flush() | |
{ | |
if (_buffer.Length <= 0) return; | |
if (_isError) | |
Debug.LogError(_buffer.ToString()); | |
else | |
Debug.Log(_buffer.ToString()); | |
_buffer.Length = 0; | |
} | |
public override void Write(string value) | |
{ | |
if (string.IsNullOrEmpty(value)) | |
return; | |
_buffer.Append(value); | |
var len = value.Length; | |
if (len <= 0) return; | |
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Suggestion of Rich Wepner : I guess you probably want to do the same thing with Console.SetErr as well? 💡