unity使用协程实现打字效果

本文介绍如何在Unity中使用协程实现文字打字效果。通过遍历字符串并逐字符显示,配合WaitForSeconds函数控制延迟,实现字幕逐字出现的动画。在Update方法中检查当前状态,以便在文字播放完成后开始新的字幕或者播放动画。

    int m_tempIndex = -1;// 字幕数组的index
    bool m_finishOne = false;// 完成一列字
    bool m_isFontPlaying = true;// 正在播放字
    string[] m_tempContent = null;// 临时存储表中的字幕
    IEnumerator PlayText()
    {// 打字
        for (int i=0;i< m_tempContent[m_tempIndex].Length;++i)
        {
            if (m_tempIndex < m_contentArral.Length && m_tempIndex >= 0)
            {
                m_contentArral[m_tempIndex].text += m_tempContent[m_tempIndex][i];
                yield return new WaitForSeconds(0.12f);
            }
        }
        m_finishOne = true;


    }
    public void Update()
    {
        if (m_finishOne)
        {// 完成一个
            m_finishOne = false;
            m_isFontPlaying = false;
        }
        if (!m_isFontPlaying)
        {// 没有正在写字
            if (m_tempIndex < m_contentArral.Length - 1)
            {
                m_isFontPlaying = true;
                m_tempIndex++;
                StartCoroutine(this.PlayText());
            }
            else
            {
                this.Destroy();
            }
        }
        if (m_isPlayAnimation)
        {// 开始播放动画
            m_isPlayAnimation = false;
            if (m_anim.clip != null)
            {
                m_isPlaying = true;
                m_hideTime = TimeWrap.time + m_anim.clip.length;
            }
        }
        if (m_isPlaying && TimeWrap.time > m_hideTime)
        {// 正在播放动画,时间结束,
            m_isPlaying = false;
            //this.Destroy();
            m_tempIndex = 0;
            if (m_tempContent != null && m_tempIndex < m_tempContent.Length)
            {// m_tempIndex符合数组长度,开启协程打字
                StartCoroutine(this.PlayText());
            }
        }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值