Typewriter.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using UnityEngine;
  3. using System.Collections;
  4. using UnityEngine.UI;
  5. public class Typewriter : MonoBehaviour
  6. {
  7. /// <summary>
  8. /// 打字速度
  9. /// </summary>
  10. public float TypeSpeed = 0.2f;
  11. public Text Showtext;
  12. /// <summary>
  13. /// 文本内容字符串
  14. /// </summary>
  15. public string StringContent = "";
  16. /// <summary>
  17. /// 当前文字位置(当前的最后一个字)
  18. /// </summary>
  19. private int curPos;
  20. void Awake()
  21. {
  22. Showtext = this.GetComponent<Text>();
  23. }
  24. private void Start()
  25. {
  26. }
  27. [ContextMenu("SetContent")]
  28. /// <summary>
  29. /// 设置内容
  30. /// </summary>
  31. public void SetContent()
  32. {
  33. StringContent = Showtext.text;
  34. curPos = 0;
  35. Debug.Log("文本内容:" + StringContent.Length);
  36. Showtext.text = string.Empty;
  37. InvokeRepeating("Typing", 0, TypeSpeed);
  38. }
  39. public void Pause()
  40. {
  41. CancelInvoke("Typing");
  42. }
  43. void Typing()
  44. {
  45. if (StringContent.Length - 1 == curPos) //如果当前字符位置等于字符总长度前一个位置就停止调用打字方法
  46. CancelInvoke("Typing");
  47. if (curPos < StringContent.Length)
  48. {
  49. Showtext.text += StringContent.Substring(curPos, 1); //每次都截取到当前位置的下一个字符位置
  50. curPos++;
  51. }
  52. }
  53. }