UGUI—倒计时Text

作者:追风剑情 发布于:2019-10-16 17:49 分类:Unity3d

示例

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using UnityEngine.Serialization;
  7. using UnityEngine.Events;
  8. using UnityEngine.EventSystems;
  9.  
  10. /// <summary>
  11. /// 倒计时Text
  12. /// </summary>
  13. public class UICountdownText : MonoBehaviour
  14. {
  15. [SerializeField]
  16. private Text m_Text;
  17. [SerializeField]
  18. private int m_RemainSecond; //剩余时间(单位:秒)
  19. private int second;
  20. private int minute;
  21. private int hour;
  22. private float startTime;
  23. private float endTime;
  24. private float lastTime;
  25. private bool m_Play = false;
  26.  
  27. [Serializable]
  28. public class OnFinishedEvent : UnityEvent { }
  29.  
  30. // 防止序列化变量重命名后丢失引用
  31. [FormerlySerializedAs("onFinished")]
  32. [SerializeField]
  33. private OnFinishedEvent m_OnFinished = new OnFinishedEvent();
  34.  
  35. void Awake()
  36. {
  37. if (m_Text == null)
  38. m_Text = this.GetComponent<Text>();
  39. SetRemainSecond(m_RemainSecond);
  40. }
  41.  
  42. void Update()
  43. {
  44. if (!m_Play)
  45. return;
  46.  
  47. if (Time.time - lastTime < 1)
  48. return;
  49. lastTime = Time.time;
  50.  
  51. string cd = string.Empty;
  52. if (hour > 0) {
  53. cd = string.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
  54. }else if(minute > 0){
  55. cd = string.Format("{0:D2}:{1:D2}", minute, second);
  56. }else{
  57. cd = string.Format("{0:D2}", second);
  58. }
  59.  
  60. if (m_Text != null)
  61. m_Text.text = cd;
  62. CalculateTime();
  63.  
  64. if (m_RemainSecond < 0)
  65. {
  66. m_Play = false;
  67. m_OnFinished.Invoke();
  68. }
  69. }
  70.  
  71. public void SetRemainSecond(int value)
  72. {
  73. m_RemainSecond = value;
  74. startTime = Time.time;
  75. endTime = startTime + m_RemainSecond;
  76. m_Play = true;
  77. CalculateTime();
  78. }
  79.  
  80. public void SetColor(Color color)
  81. {
  82. if (m_Text != null)
  83. m_Text.color = color;
  84. }
  85.  
  86. private void CalculateTime()
  87. {
  88. m_RemainSecond = (int)(endTime - Time.time);
  89. second = m_RemainSecond % 60;
  90. minute = (m_RemainSecond / 60) % 60;
  91. hour = (m_RemainSecond / 3600);
  92. }
  93. }


运行测试
22222.gif

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号