ConsoleToScreen.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using UnityEngine;
  2. public class ConsoleToScreen : MonoBehaviour
  3. {
  4. const int maxLines = 50;
  5. const int maxLineLength = 120;
  6. private string _logStr = "";
  7. private Vector2 _scrollPosition;
  8. public int fontSize = 15;
  9. private void OnEnable()
  10. {
  11. Application.logMessageReceived += HandleLog;
  12. }
  13. private void OnDisable()
  14. {
  15. Application.logMessageReceived -= HandleLog;
  16. }
  17. private void HandleLog(string logString, string stackTrace, LogType type)
  18. {
  19. var lines = logString.Split('\n');
  20. foreach (var line in lines)
  21. {
  22. if (line.Length <= maxLineLength)
  23. {
  24. _logStr += line + "\n";
  25. }
  26. else
  27. {
  28. var startIndex = 0;
  29. while (startIndex < line.Length)
  30. {
  31. var length = Mathf.Min(maxLineLength, line.Length - startIndex);
  32. _logStr += line.Substring(startIndex, length) + "\n";
  33. startIndex += maxLineLength;
  34. }
  35. }
  36. }
  37. if (_logStr.Split('\n').Length > maxLines)
  38. {
  39. var linesToRemove = _logStr.Split('\n').Length - maxLines;
  40. var firstNewLineIndex = _logStr.IndexOf('\n');
  41. _logStr = _logStr.Remove(0, firstNewLineIndex + 1);
  42. }
  43. }
  44. private void Update()
  45. {
  46. // 自动滚动到底部
  47. _scrollPosition.y = Mathf.Infinity;
  48. }
  49. private void OnGUI()
  50. {
  51. GUILayout.BeginArea(new Rect(10f, 10f, Screen.width - 20f, Screen.height - 20f));
  52. _scrollPosition = GUILayout.BeginScrollView(_scrollPosition, GUIStyle.none, GUIStyle.none);
  53. GUIStyle style = new GUIStyle(GUI.skin.label);
  54. style.fontSize = fontSize;
  55. GUILayout.Label(_logStr, style);
  56. GUILayout.EndScrollView();
  57. GUILayout.EndArea();
  58. }
  59. }