Text 横向滚动——跑马灯效果

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

[RequireComponent(typeof(Mask))]
public class TextHorizonScroller : MonoBehaviour
{
    //两个文本之间的间隔
    public float deltaLength = 100f;
    //滚动的速度
    public float scrollSpeed = 1f;
    //文本1
    public Text text1;
    //文本2
    public Text text2;
    //遮罩
    private Mask mask;
    //是否是富文本格式
    public bool isRich;
    private bool needScroll = false;
    private int textLength;

    //外部传参
    public void SetText(string text)
    {
        mask = GetComponent();
        if (text1 == null || text2 == null)
        {
            return;
        }
        text1.rectTransform.anchoredPosition = new Vector2(0f, text1.rectTransform.anchoredPosition.y);
        text2.rectTransform.anchoredPosition = new Vector2(0f, text2.rectTransform.anchoredPosition.y);
        text1.text = text;
        float maskLength = mask.rectTransform.sizeDelta.x;
        textLength = CalculateLengthOfText(text1.text, text1);
        text1.rectTransform.sizeDelta = new Vector2(textLength, text1.rectTransform.sizeDelta.y);
        if (textLength > maskLength)
        {
            text2.rectTransform.anchoredPosition = text1.rectTransform.anchoredPosition + new Vector2(textLength + deltaLength, 0);
            text2.rectTransform.sizeDelta = text1.rectTransform.sizeDelta;
            text2.text = text1.text;
            needScroll = true;
        }
        else
        {
            text2.text = string.Empty;
            needScroll = false;
            text1.rectTransform.sizeDelta = mask.rectTransform.sizeDelta;
        }
    }

    void Update()
    {
        if (needScroll)
        {
            ScrollText(text1, text2);
            ScrollText(text2, text1);
        }
    }

    //更新目标文本的位置
    private void ScrollText(Text targetText, Text anotherText)
    {
        targetText.rectTransform.anchoredPosition -= new Vector2(1f, 0f) * scrollSpeed;
        if (targetText.rectTransform.anchoredPosition.x < -1 * targetText.rectTransform.sizeDelta.x)
        {
            targetText.rectTransform.anchoredPosition = anotherText.rectTransform.anchoredPosition + new Vector2(textLength + deltaLength, 0);
        }
    }

    //计算文本的长度
    private int CalculateLengthOfText(string message, Text tex)
    {
        if (isRich)
        {
            return (int)tex.preferredWidth;
        }
        int totalLength = 0;
        Font myFont = tex.font;
        myFont.RequestCharactersInTexture(message, tex.fontSize, tex.fontStyle);
        CharacterInfo characterInfo = new CharacterInfo();

        char[] arr = message.ToCharArray();

        foreach (char c in arr)
        {
            myFont.GetCharacterInfo(c, out characterInfo, tex.fontSize);

            totalLength += characterInfo.advance;
        }

        return totalLength;
    }

}

 

你可能感兴趣的:(Text 横向滚动——跑马灯效果)