Typewriter.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public bool IsOver;
  21. void Awake()
  22. {
  23. Showtext = this.GetComponent<Text>();
  24. IsOver = true;
  25. }
  26. private void Start()
  27. {
  28. }
  29. [ContextMenu("SetContent")]
  30. /// <summary>
  31. /// 设置内容
  32. /// </summary>
  33. public void SetContent()
  34. {
  35. // StringContent = Showtext.text;
  36. curPos = 0;
  37. Debug.Log("文本内容:" + StringContent.Length);
  38. Showtext.text = string.Empty;
  39. InvokeRepeating("Typing", 0, TypeSpeed);
  40. IsOver = false;
  41. }
  42. public void Pause()
  43. {
  44. CancelInvoke("Typing");
  45. }
  46. void Typing()
  47. {
  48. if (StringContent.Length - 1 == curPos) //如果当前字符位置等于字符总长度前一个位置就停止调用打字方法
  49. {
  50. CancelInvoke("Typing");
  51. IsOver = true;
  52. }
  53. if (curPos < StringContent.Length)
  54. {
  55. Showtext.text += StringContent.Substring(curPos, 1); //每次都截取到当前位置的下一个字符位置
  56. curPos++;
  57. }
  58. }
  59. }