1. 日期:2020/11/20 16:56:23
    2. 功能:打字机功能
    3. *****************************************************/
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6. public class TxtTools : MonoBehaviour
    7. {
    8. [Header("打字间隔")]public float typeTimer=0.2f;
    9. [Header("打字的内容")]public string words;
    10. private Text txtFile;
    11. private bool isStartTyping=true;//是否开始打字
    12. private float timer;
    13. private int currentIndex = 0;
    14. private void Start()
    15. {
    16. txtFile = GetComponent<Text>();
    17. //返回两个或多个值中最大的值
    18. typeTimer = Mathf.Max(0.02f, typeTimer);
    19. }
    20. private void Update()
    21. {
    22. OnStartTyping();
    23. }
    24. private void OnStartTyping()
    25. {
    26. if (isStartTyping)
    27. {
    28. timer += Time.deltaTime;
    29. if (timer >= typeTimer)
    30. {
    31. timer = 0;
    32. currentIndex++;
    33. txtFile.text = words.Substring(0,currentIndex);
    34. if (currentIndex>=words.Length)
    35. {
    36. OnFinshTyping();
    37. }
    38. }
    39. }
    40. }
    41. private void OnFinshTyping()
    42. {
    43. isStartTyping = false;
    44. timer = 0;
    45. currentIndex = 0;
    46. txtFile.text = words;
    47. }
    48. }