计时器_C#

利用dataTime写计时器功能

  public Text text;
        public float speed = 1;
        public bool isStart = false;
        private float beforeTime;
        private DateTime time;
        private void StartTime()
        {
            isStart = true;
            beforeTime = Time.time;
            time = new DateTime();

            StopAllCoroutines();
            StartCoroutine(CountTime());
        }
        private void EndTime()
        {
            isStart = false;
        }
        private IEnumerator CountTime()
        {
            while (true)
            {
                float offset = Time.time - beforeTime;
                time = time.AddMilliseconds(offset * speed);
                text.text = time.ToString("HH:mm:ss");
                yield return null;
                if (!isStart) break;
            }
        }
        public void FixedUpdate()
        {
#if UNITY_EDITOR
            if (Input.GetKeyDown(KeyCode.Q))
            {
                StartTime();
            }
            if (Input.GetKeyDown(KeyCode.A))
            {
                EndTime();
            }
#endif
            if (isStart)
            {
                float offset = Time.time - beforeTime;
                time = time.AddMilliseconds(offset * speed);
                text.text = time.ToString("HH:mm:ss");
            }
        }

猜你喜欢

转载自blog.csdn.net/wxxqhf/article/details/85004095