DebugHelper.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (C) 2015 Christoph Kutza
  3. *
  4. * Please refer to the LICENSE file for license information
  5. */
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using UnityEngine;
  11. /// <summary>
  12. /// Shows the console on all platforms. For debugging.
  13. /// </summary>
  14. public class DebugHelper
  15. {
  16. public static bool sShowConsole = false;
  17. public static bool sConsoleAutoScroll = true;
  18. private static Vector2 mDebugConsoleScrollPos = new Vector2();
  19. private static StringBuilder mLog = null;
  20. private static int mLines = 0;
  21. public static void ActivateConsole()
  22. {
  23. if (mLog != null)
  24. return;
  25. mLog = new StringBuilder();
  26. Application.logMessageReceived += LogType;
  27. }
  28. private static void LogType(string condition, string stackTrace, LogType type)
  29. {
  30. int lines = 0;
  31. mLog.Append(condition);
  32. if (type == UnityEngine.LogType.Exception)
  33. {
  34. lines += stackTrace.Count((x) => { return x == '\n'; });
  35. mLog.Append(stackTrace);
  36. }
  37. mLog.Append("\n");
  38. lines++;
  39. mLines += lines;
  40. int foundLines = 0;
  41. for (int i = mLog.Length - 1; i >= 0; i--)
  42. {
  43. if (mLog[i] == '\n')
  44. {
  45. foundLines++;
  46. if (foundLines == 100)
  47. {
  48. mLog.Remove(0, i + 1);
  49. break;
  50. }
  51. }
  52. }
  53. }
  54. public static void DrawConsole()
  55. {
  56. if (mLog == null)
  57. return;
  58. if (sShowConsole == false)
  59. {
  60. if (GUI.Button(new Rect(Screen.width - 40*2, Screen.height - 20*2, 40*2, 20*2), "Show"))
  61. {
  62. sShowConsole = true;
  63. }
  64. }
  65. else
  66. {
  67. if (GUI.Button(new Rect(Screen.width - 40*2, Screen.height * 0.75f - 20*2, 40*2, 20*2), "Hide"))
  68. {
  69. sShowConsole = false;
  70. }
  71. if (GUI.Button(new Rect(Screen.width - 90*2, Screen.height * 0.75f - 20*2, 40*2, 20*2), "Auto"))
  72. {
  73. sConsoleAutoScroll = !sConsoleAutoScroll;
  74. }
  75. GUIStyle textStyle = new GUIStyle();
  76. textStyle.normal.textColor = Color.white;
  77. textStyle.richText = true;
  78. GUI.Box(new Rect(0, Screen.height * 0.75f, Screen.width, Screen.height * 0.25f), "");
  79. GUILayout.BeginArea(new Rect(0, Screen.height * 0.75f, Screen.width, Screen.height * 0.25f));
  80. mDebugConsoleScrollPos = GUILayout.BeginScrollView(mDebugConsoleScrollPos);
  81. if(sConsoleAutoScroll)
  82. mDebugConsoleScrollPos = new Vector2(0, 1000000000);
  83. GUILayout.TextArea(mLog.ToString(), textStyle);
  84. GUILayout.EndScrollView();
  85. GUILayout.EndArea();
  86. }
  87. }
  88. }