unity 实现字幕效果

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

public class ZiMu : MonoBehaviour
{
    [Header("UI 组件")]
   // public Text tishi;
    public Text _TextLabel;//文本框
    public Transform bg_imaPanel;

    [Header("文本文件")]
    public TextAsset _TextFile;
    public int _Index;//序号
    //字符显示速度
    public float _TextSpeed = 0.1f;
    //字符是否显示完毕布尔
    bool _bTextFinished;
    //是否取消当前独字输入
    bool _bCacelTyping;
    bool po = false;
    //文本列表
    List<string> _TextList = new List<string>();

    void Awake()
    {
        GetTextFormFile(_TextFile);
        _Index = 0;//序列归零
    }
    private void OnEnable()
    {
        //字符是否显示完毕布尔
        _bTextFinished = true;
        _Index = 0;//序列归零
                   //开启协程
        StartCoroutine(SetTextUI());
    }

    void Update()
    {

        if (_Index == _TextList.Count)
        {
            transform.gameObject.SetActive(false);
            _Index = 0;//序列归零
            
            bg_imaPanel .gameObject.SetActive(true);
            return;
        }
        if (po)
        {
            //若是正在执行独字输出而且没有取消当前独字输入
            if (_bTextFinished && !_bCacelTyping)
            {
                //开启 文本输出方法
                StartCoroutine(SetTextUI());
            }
            //若是已经开始执行文本输出方法 就设置独字输入布尔
            else if (!_bTextFinished)
            {
                _bCacelTyping = !_bCacelTyping;
            }
        }

    }

    //文件读取方法
    private void GetTextFormFile(TextAsset _Flie)
    {
        _TextList.Clear();
        _Index = 0;

        //逐行读取文本文件
        var _LineDate = _Flie.text.Split('\n');
        foreach (var _Line in _LineDate)
        {
            _TextList.Add(_Line);
        }
    }

    //文本输出方法
    public IEnumerator SetTextUI()
    {
        //文本正在输出
        _bTextFinished = false;
        _TextLabel.text = "";
        po = false;
        int _letter = 0;
        //若是不知足当前条件
        while (!_bCacelTyping && _letter < _TextList[_Index].Length - 1)
        {
            //累加字符显示
            _TextLabel.text += _TextList[_Index][_letter];
            _letter++;
            //协程等待时间
            yield return new WaitForSeconds(_TextSpeed);
        }
        po = true;
        //就直接输出当前文本行文本
        //_TextLabel.text = _TextList[_Index];

        _bCacelTyping = false;
        //文本输出完毕
        _bTextFinished = true;
        //序号增长
        _Index++;
    }
}

猜你喜欢

转载自blog.csdn.net/LiPing122335/article/details/123851935
今日推荐