Tooltip.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using TMPro;
  6. using KairoEngine.UI;
  7. using Sirenix.OdinInspector;
  8. namespace KairoEngine.UI.Tooltips
  9. {
  10. [HideMonoScript, ExecuteInEditMode()]
  11. public class Tooltip : MonoBehaviour
  12. {
  13. public TextMeshProUGUI headerField;
  14. public TextMeshProUGUI contentField;
  15. public LayoutElement layoutElement;
  16. public RectTransform rectTransform;
  17. public int characterWrapLimit;
  18. public Vector2 positionOffset = new Vector2(10, 10);
  19. public string header = "";
  20. private void Awake()
  21. {
  22. if(rectTransform == null) rectTransform = GetComponent<RectTransform>();
  23. }
  24. private void Update()
  25. {
  26. if(headerField == null || contentField == null || layoutElement == null || rectTransform == null) return;
  27. if(Application.isEditor) UpdateLayout();
  28. Vector2 position = Input.mousePosition;
  29. // Todo: Position tooltip left/right/up/donw the mouse pointer dependending on size and screen position.
  30. float pivotX = position.x / Screen.width;
  31. float pivotY = position.y / Screen.height;
  32. rectTransform.pivot = new Vector2(pivotX, pivotY);
  33. position += positionOffset;
  34. transform.position = position;
  35. }
  36. public void SetText(string content, string header = "")
  37. {
  38. if(string.IsNullOrEmpty(header)) headerField.gameObject.SetActive(false);
  39. else
  40. {
  41. this.header = header;
  42. headerField.text = header;
  43. headerField.gameObject.SetActive(true);
  44. }
  45. contentField.text = content;
  46. UpdateLayout();
  47. }
  48. public void UpdateLayout()
  49. {
  50. int headerLength = headerField.text.Length;
  51. int contentLength = contentField.text.Length;
  52. layoutElement.enabled = (headerLength > characterWrapLimit || contentLength > characterWrapLimit) ? true : false;
  53. }
  54. }
  55. }