TextScroll.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using TMPro;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. [RequireComponent(typeof(Mask))]
  5. [RequireComponent(typeof(Image))]
  6. public class TextScroll : MonoBehaviour
  7. {
  8. private TextMeshProUGUI txt;
  9. private Text txt1;
  10. private RectTransform rtf;
  11. private RectTransform rtfTxt;
  12. private bool isScroll;
  13. private float scrollLen;
  14. private float curPosx;
  15. private float scrollSpeed = 20;
  16. public void Awake()
  17. {
  18. rtf = GetComponent<RectTransform>();
  19. txt = rtf.GetChild(0).GetComponent<TextMeshProUGUI>();
  20. txt1 = rtf.GetChild(0).GetComponent<Text>();
  21. }
  22. public void CheckScroll()
  23. {
  24. var cttWidth = rtf.rect.width;
  25. float len = 0;
  26. if (txt != null)
  27. {
  28. len = txt.preferredWidth;
  29. rtfTxt = txt.rectTransform;
  30. }
  31. else if (txt1 != null)
  32. {
  33. len = txt1.preferredWidth;
  34. rtfTxt = txt1.rectTransform;
  35. }
  36. isScroll = len != 0 && (cttWidth < len);
  37. if (isScroll)
  38. {
  39. rtfTxt.pivot = new Vector2(0, 0.5f);
  40. rtfTxt.anchoredPosition = Vector2.zero;
  41. scrollLen = -(len - cttWidth);
  42. curPosx = 0;
  43. }
  44. }
  45. public void Update()
  46. {
  47. if (!isScroll) return;
  48. curPosx -= Time.deltaTime * scrollSpeed;
  49. rtfTxt.anchoredPosition = new Vector2(curPosx, 0);
  50. if (curPosx < scrollLen)
  51. {
  52. curPosx = 0;
  53. }
  54. }
  55. }