ScreenText.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. namespace DunGen.Demo
  4. {
  5. public class ScreenText : MonoBehaviour
  6. {
  7. #region Helper Class
  8. private sealed class ScreenTextData
  9. {
  10. public string Text;
  11. public float Timer;
  12. }
  13. #endregion
  14. public GUIStyle Style = new GUIStyle();
  15. public float MessageFadeTime = 5;
  16. private readonly List<ScreenTextData> messages = new List<ScreenTextData>();
  17. public void AddMessage(string message)
  18. {
  19. messages.Add(new ScreenTextData() { Text = message, Timer = MessageFadeTime });
  20. }
  21. private void Update()
  22. {
  23. for (int i = messages.Count - 1; i >= 0; i--)
  24. {
  25. var message = messages[i];
  26. if (message.Timer > 0)
  27. {
  28. message.Timer -= Time.deltaTime;
  29. if (message.Timer <= 0)
  30. messages.RemoveAt(i);
  31. }
  32. }
  33. }
  34. private void OnGUI()
  35. {
  36. Vector2 bottomRight = GUIUtility.ScreenToGUIPoint(new Vector2(Screen.width, Screen.height));
  37. float bufferSize = 5;
  38. bottomRight -= new Vector2(bufferSize, bufferSize);
  39. for (int i = messages.Count - 1; i >= 0; i--)
  40. {
  41. var msg = messages[i];
  42. GUIContent content = new GUIContent(msg.Text);
  43. Vector2 stringSize = GUI.skin.label.CalcSize(content);
  44. GUI.Label(new Rect(bottomRight.x - stringSize.x, bottomRight.y - stringSize.y, stringSize.x, stringSize.y), content, Style);
  45. bottomRight -= new Vector2(0, stringSize.y + bufferSize);
  46. }
  47. }
  48. #region Static Methods
  49. public static void Log(object obj)
  50. {
  51. ScreenText.Log(obj.ToString());
  52. }
  53. public static void Log(string format, params object[] args)
  54. {
  55. var component = UnityUtil.FindObjectByType<ScreenText>();
  56. if (component == null)
  57. return;
  58. component.AddMessage(string.Format(format, args));
  59. }
  60. #endregion
  61. }
  62. }