ConsoleToScreen.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public class ConsoleToScreen : MonoBehaviour
  6. {
  7. const int maxLines = 50;
  8. const int maxLineLength = 120;
  9. private string _logStr = "";
  10. private readonly List<string> _lines = new List<string>();
  11. public int fontSize = 15;
  12. void OnEnable() { Application.logMessageReceived += Log; }
  13. void OnDisable() { Application.logMessageReceived -= Log; }
  14. public void Log(string logString, string stackTrace, LogType type)
  15. {
  16. foreach (var line in logString.Split('\n'))
  17. {
  18. if (line.Length <= maxLineLength)
  19. {
  20. _lines.Add(line);
  21. continue;
  22. }
  23. var lineCount = line.Length / maxLineLength + 1;
  24. for (int i = 0; i < lineCount; i++)
  25. {
  26. if ((i + 1) * maxLineLength <= line.Length)
  27. {
  28. _lines.Add(line.Substring(i * maxLineLength, maxLineLength));
  29. }
  30. else
  31. {
  32. _lines.Add(line.Substring(i * maxLineLength, line.Length - i * maxLineLength));
  33. }
  34. }
  35. }
  36. if (_lines.Count > maxLines)
  37. {
  38. _lines.RemoveRange(0, _lines.Count - maxLines);
  39. }
  40. _logStr = string.Join("\n", _lines);
  41. }
  42. void OnGUI()
  43. {
  44. GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
  45. new Vector3(Screen.width / 1200.0f, Screen.height / 800.0f, 1.0f));
  46. GUI.Label(new Rect(10, 10, 800, 370), _logStr, new GUIStyle() { fontSize = Math.Max(10, fontSize) });
  47. }
  48. }