Unity打字机效果扩展使支持富文本

前段时间策划在打字机的文本中配置了富文本,修改某些文字的颜色,但是公司原有的代码只有基础的打字机效果,不支持富文本,代码逻辑就是将文本转换位字符数组,然后再Update中根据间隔拼接字符串显示文本。

基本打字机主要代码逻辑:

if (_isPlaying)
            {
                _timer += Time.deltaTime;

                if (_timer >= Interval)
                {
                    _timer = 0;
                    //
                    _text.text = _text.text + _typingList[_index];
                    _index++;

                    if (_index >= _typingList.Count)
                    {
                        _isPlaying = false;

                        if (onTypingFinish != null)
                        {
                            Action doo = onTypingFinish;
                            doo();
                            onTypingFinish = null;
                        }
                    }

                }

            }

如果文本配置了富文本,这个方法会将标签内容显示出来,造成文本显示不正确。

要支持富文本的话,有个简单的办法,先找到富文本开始标签:<color=#,文本后边再加上结束标签:</color>,中间拼接上需要改变颜色的文本元素,这样就可以将带有富文本的文本显示出来了。

代码如下:

private void DoType()
        {
            if (!_isPlaying)
            {
                return;
            }
            _timer += Time.deltaTime;
            if (_timer < Interval)
            {
                return;
            }
           
            _timer = 0;
            if (_typeData[_index] =='<' && _typeData.Substring(_index, 8).Equals("<color=#"))//<color=#7FB05E>  15
            {
                m_curShowText += _typeData.Substring(_index,15);
                _index += 15;
                m_curRichType = "</color>";
            }
            else if (_typeData[_index] == '<' && _typeData.Substring(_index, 8).Equals("</color>"))//</color>   8
            {
                _index += 8;
                m_curRichType = "";
                m_curShowText += "</color>";
            }

            m_curShowText += _typeData[_index];

            _text.text = m_curShowText + m_curRichType;
            _index++;

            if (_index >= _typeData.Length)
            {
                _isPlaying = false;
                if (onTypingFinish != null)
                {
                    Action doo = onTypingFinish;
                    doo();
                    onTypingFinish = null;
                }
            }
        }

扩展:按照这个逻辑,也可以扩展字体大小等富文本。

不足:该方法代码实现不灵活,颜色标签里面的参数不支持颜色名字,可以修改为正则表达式。

猜你喜欢

转载自blog.csdn.net/qq_33461689/article/details/123694446