using System.Collections; using TMPro; using UnityEngine; [RequireComponent(typeof(TMP_Text))] public class MarqueeText : MonoBehaviour { public float speed = 14f; public float pauseStart = 1.8f; public float pauseEnd = 0.9f; private TMP_Text _label; private RectTransform _rect; private Coroutine _scrollRoutine; private void Awake() { _label = GetComponent(); _rect = GetComponent(); } private IEnumerator Start() { yield return null; Refresh(); } private void OnDisable() { StopScrolling(); } public void Refresh() { if (!isActiveAndEnabled || _label == null || _rect == null || transform.parent == null) return; StopScrolling(); SetX(0f); _label.ForceMeshUpdate(); float textW = _label.preferredWidth; float containerW = ((RectTransform)transform.parent).rect.width; float dist = textW - containerW; if (dist > 1f) _scrollRoutine = StartCoroutine(ScrollLoop(dist)); } private IEnumerator ScrollLoop(float dist) { while (true) { SetX(0f); yield return new WaitForSeconds(pauseStart); float x = 0f; while (x > -dist) { x = Mathf.MoveTowards(x, -dist, speed * Time.deltaTime); SetX(x); yield return null; } yield return new WaitForSeconds(pauseEnd); } } private void SetX(float x) => _rect.anchoredPosition = new Vector2(x, _rect.anchoredPosition.y); private void StopScrolling() { if (_scrollRoutine == null) return; StopCoroutine(_scrollRoutine); _scrollRoutine = null; } }