1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using TMPro;
- using UnityEngine;
- using UnityEngine.UI;
- [RequireComponent(typeof(Mask))]
- [RequireComponent(typeof(Image))]
- public class TextScroll : MonoBehaviour
- {
- private TextMeshProUGUI txt;
- private Text txt1;
- private RectTransform rtf;
- private RectTransform rtfTxt;
- private bool isScroll;
- private float scrollLen;
- private float curPosx;
- private float scrollSpeed = 20;
- public void Awake()
- {
- rtf = GetComponent<RectTransform>();
- txt = rtf.GetChild(0).GetComponent<TextMeshProUGUI>();
- txt1 = rtf.GetChild(0).GetComponent<Text>();
- }
- public void CheckScroll()
- {
- var cttWidth = rtf.rect.width;
- float len = 0;
- if (txt != null)
- {
- len = txt.preferredWidth;
- rtfTxt = txt.rectTransform;
- }
- else if (txt1 != null)
- {
- len = txt1.preferredWidth;
- rtfTxt = txt1.rectTransform;
- }
- isScroll = len != 0 && (cttWidth < len);
- if (isScroll)
- {
- rtfTxt.pivot = new Vector2(0, 0.5f);
- rtfTxt.anchoredPosition = Vector2.zero;
- scrollLen = -(len - cttWidth);
- curPosx = 0;
- }
- }
- public void Update()
- {
- if (!isScroll) return;
- curPosx -= Time.deltaTime * scrollSpeed;
- rtfTxt.anchoredPosition = new Vector2(curPosx, 0);
- if (curPosx < scrollLen)
- {
- curPosx = 0;
- }
- }
- }
|