Unity Text文字逐个播放

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

public class AutoText : MonoBehaviour
{
    string str = "";        //要显示的所有字符串
    string s = "";          //每次显示的字符串
    float time = 0.05f;     //每个文字显示时间间隔
    Text text;
    Coroutine cor;

    void Update()
    {
        //开启播放后,点击鼠标左键或任意按键则显示全部文本
        if (cor != null && (Input.GetMouseButtonDown(0) || Input.anyKeyDown))
        {
            Finish();
        }
    }

    /// <summary>
    /// 调用协成实现一个字一个字冒出的效果
    /// </summary>
    public void PlayText(string content = null, float time = 0.05f)
    {
        text = GetComponent<Text>();
        str = text.text;
        //重置
        if (!string.IsNullOrEmpty(content))
        {
            str = content;
        }
        this.time = time;
        text.text = "";
        s = "";

        //当前有协成,则先关闭
        if (cor != null)
        {
            StopCoroutine(cor);
        }
        //开启协成
        cor = StartCoroutine(ShowText(str.Length));
    }

    IEnumerator ShowText(int strLength)
    {
        int i = 0;
        while (i < strLength)
        {
            yield return new WaitForSeconds(time);
            s += str[i].ToString();
            text.text = s;
            i += 1;
        }
        //显示完成,停止协成
        Finish();
    }

    //立刻显示所有文字
    public void Finish()
    {
        s = str;
        text.text = s;
        if (cor != null)
        {
            StopCoroutine(cor);
            cor = null;
        }
    }
}

调用

        /// <summary>
        /// 逐字播放
        /// </summary>
        public static void PlayAutoText(GameObject go, string content = null, float time = 0.05f)
        {
            if (go != null)
            {
                Text text = go.GetComponent<Text>();
                if (text != null)
                {
                    AutoText autoText = go.GetComponent<AutoText>();
                    if (autoText == null)
                    {
                        autoText = go.AddComponent<AutoText>();
                    }
                    autoText.PlayText(content, time);
                    return;
                }
            }
        }

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值