ManagerLog.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.Serialization;
  4. using System;
  5. using System.Text;
  6. using System.Collections;
  7. using Random = UnityEngine.Random;
  8. public class ManagerLog : MonoBehaviour
  9. {
  10. #region 变量
  11. private Text LogText;
  12. private ScrollRect LogScrollRect;
  13. private int LogCount;
  14. private int LogCapacityInitial;
  15. private bool ShowBottom;
  16. public static ManagerLog Ins;
  17. #endregion
  18. private void Start()
  19. {
  20. ShowBottom = true;
  21. }
  22. private void Awake()
  23. {
  24. LogText = ManagerResource.Ins.LogLabel;
  25. LogScrollRect = ManagerResource.Ins.LogScrollRect;
  26. Ins = this;
  27. LogCapacityInitial = LogText.text.Split('\n').Length;
  28. }
  29. private void FixedUpdate()
  30. {
  31. if (ShowBottom)
  32. {
  33. ShowBottom = false;
  34. LogScrollRect.verticalNormalizedPosition = 0;
  35. }
  36. }
  37. public void AddMessage(string message)
  38. {
  39. if (LogCount < LogCapacityInitial)
  40. {
  41. string[] contents = LogText.text.Split('\n');
  42. LogText.text = "";
  43. Sort(contents, message);
  44. for (int i = 0; i < LogCapacityInitial; i++)
  45. {
  46. if (i == LogCapacityInitial - 1)
  47. {
  48. LogText.text = LogText.text + contents[i];
  49. }
  50. else
  51. {
  52. LogText.text = LogText.text + contents[i] + '\n';
  53. }
  54. }
  55. }
  56. else
  57. {
  58. LogText.text = LogText.text + '\n' + message;
  59. }
  60. LogCount++;
  61. if (Math.Abs(LogScrollRect.verticalNormalizedPosition) < 0.01f)
  62. {
  63. ShowBottom = true;
  64. }
  65. }
  66. private void Sort(string[] strings, string message)
  67. {
  68. for (int i = 0; i < strings.Length - 1; i++)
  69. {
  70. strings[i] = strings[i + 1];
  71. }
  72. strings[strings.Length - 1] = message;
  73. }
  74. }