123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- using System;
- using UnityEngine;
- using System.Collections;
- using System.Text;
- using Unity.VisualScripting;
- using UnityEngine.UI;
- public class Typewriter : MonoBehaviour
- {
- /// <summary>
- /// 打字速度
- /// </summary>
- public float TypeSpeed = 0.2f;
- public Text Showtext;
- /// <summary>
- /// 文本内容字符串
- /// </summary>
- public string StringContent = "";
- /// <summary>
- /// 当前文字位置(当前的最后一个字)
- /// </summary>
- private int curPos;
- public bool IsOver;
- void Awake()
- {
- Showtext = this.GetComponent<Text>();
- IsOver = true;
- }
- private void Start()
- {
- }
- /// <summary>
- /// 设置内容
- /// </summary>
- [ContextMenu("SetContent")]
- public void SetContent()
- {
- if (StringContent.Length == 0)
- {
- StringContent = Showtext.text;
- }
- curPos = 0;
- Showtext.text = string.Empty;
- InvokeRepeating("Typing", 0, TypeSpeed);
- IsOver = false;
- }
- public void Pause()
- {
- CancelInvoke("Typing");
- }
- void Typing()
- {
- if (StringContent.Length - 1 == curPos) //如果当前字符位置等于字符总长度前一个位置就停止调用打字方法
- {
- CancelInvoke("Typing");
- IsOver = true;
- }
- // ASCIIEncoding ascii = new ASCIIEncoding();
- //
- // int tempLen = 0;
- //
- // byte[] s = ascii.GetBytes(StringContent.Substring(curPos, 1));
- //
- // for (int i = 0; i < s.Length; i++)
- // {
- // if (s[i] == 63)
- // {
- // tempLen += 2;
- // }
- // else
- // {
- // tempLen += 1;
- // }
- // }
- //
- // if (tempLen == 2)
- // {
- // curPos++;
- // return;
- // }
- if (curPos < StringContent.Length)
- {
- Showtext.text += StringContent.Substring(curPos, 1); //每次都截取到当前位置的下一个字符位置
- curPos++;
- }
- }
- }
|