daziji.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. public class daziji : MonoBehaviour
  5. {
  6. public float charsPerSecond = 0.01f;//打字时间间隔
  7. private string words;//保存需要显示的文字
  8. private bool isActive = false;
  9. private float timer;//计时器
  10. private Text myText;
  11. private int currentPos = 0;//当前打字位置
  12. // Use this for initialization
  13. void Start()
  14. {
  15. Init();
  16. myText = GetComponent<Text>();
  17. words = myText.text;
  18. myText.text = "";//获取Text的文本信息,保存到words中,然后动态更新文本显示内容,实现打字机的效果
  19. }
  20. void Init()
  21. {
  22. timer = 0;
  23. isActive = true;
  24. charsPerSecond = Mathf.Max(0.01f, charsPerSecond);
  25. }
  26. // Update is called once per frame
  27. void Update()
  28. {
  29. OnStartWriter();
  30. }
  31. private void OnDisable()
  32. {
  33. Init();
  34. }
  35. public void StartEffect()
  36. {
  37. isActive = true;
  38. }
  39. /// <summary>
  40. /// 执行打字任务
  41. /// </summary>
  42. void OnStartWriter()
  43. {
  44. if (isActive)
  45. {
  46. timer += Time.deltaTime;
  47. if (timer >= charsPerSecond)
  48. {//判断计时器时间是否到达
  49. timer = 0;
  50. currentPos++;
  51. myText.text = words.Substring(0, currentPos);//刷新文本显示内容
  52. if (currentPos >= words.Length)
  53. {
  54. OnFinish();
  55. }
  56. }
  57. }
  58. }
  59. /// <summary>
  60. /// 结束打字,初始化数据
  61. /// </summary>
  62. void OnFinish()
  63. {
  64. isActive = false;
  65. timer = 0;
  66. currentPos = 0;
  67. myText.text = words;
  68. }
  69. }