1. 程式人生 > >UGUI 實現跑馬燈效果

UGUI 實現跑馬燈效果

使用Mask,遮擋走出去的文字(掛載到背景上,程式碼和要滾動的文字作為其子物體的元件)

1

using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 跑馬燈文字設定
/// </summary>
public class PaoMaDengText : MonoBehaviour {

    [SerializeField]
    private  Text pmdText;     //跑馬燈text.
    private Queue<string> pmdQueue;     //跑馬燈佇列.
    private bool isEnd = false;   //判斷當前text中的跑馬燈是否跑完.

    private void Start()
    {
        if(pmdText == null) pmdText = this.GetComponent<Text>();
        Init();
    }

    public void Init()
    {
        pmdQueue = new Queue<string>();
        AddMessage(pmdText.text);
    }

    /// <summary>
    /// 新增跑馬燈文字...
    /// </summary>
    /// <param name="msg">文字內容</param>
    public void AddMessage(string msg)
    {
        if (!gameObject.activeSelf)
        {
            gameObject.SetActive(true);
            Init();
        }
        
        pmdQueue.Enqueue(msg);    
        if (isEnd) return;
        StartCoroutine(Marquee());
    }

    public IEnumerator Marquee()
    {
        float begin_X = 200;  //第一個字開始的位置 
        float end_X = 200; 

        while (pmdQueue.Count > 0)
        {
            Vector3 pos = pmdText.rectTransform.localPosition;

            float duration = 10f;  //預設時間
            float speed = 100f;    //滾動速度
            int loop = 3;          //迴圈次數

            string msg = pmdQueue.Dequeue();
            pmdText.text = msg;
            float txetWidth = pmdText.preferredWidth;  //文字的長度...
            float distance = begin_X - end_X + txetWidth;   //自己體會...
            duration = distance / speed;

            isEnd = true;
            //Debug.Log("distance:" + -distance + " speed:" + speed + " duration:" + duration);

            while (loop-- > 0)//todo 看需求... (loop > 0)
            {
                pmdText.rectTransform.localPosition = new Vector3(begin_X, pos.y, pos.z);  //歸位...

                pmdText.rectTransform.DOLocalMoveX(-distance, duration).SetEase(Ease.Linear);  //滾動...
                yield return new WaitForSeconds(duration);
            }
            yield return null;
        }
        isEnd = false;
        gameObject.SetActive(false);
        yield break;
    }
    private void OnDisable()
    {
        StopAllCoroutines();
    }
}