UGUI 实现跑马灯效果

跑马灯,这个功能在游戏中还是很常见的,,,
UGUI 实现跑马灯效果_第1张图片
(网图)

注意要使用Mask,遮挡走出去的文字(挂载到背景上,代码和要滚动的文字作为其子物体的组件)

UGUI 实现跑马灯效果_第2张图片

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

/// 
/// 跑马灯文字设置
/// 
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);
    }

    /// 
    /// 添加跑马灯文字...
    /// 
    /// 文字内容
    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();
    }
}

你可能感兴趣的:(ジ﹋★☆『,Unity,3D,』,Unity,引擎入门)