[英]Repeating countdown timer unity
我是团结的新手。 我的目的是让倒数计时器从 5 秒开始,当它达到零后我需要从 5 开始重复。 帮我解决这个问题谢谢。 我当前的代码:
private bool stopTimer;
[HideInInspector]public float time1;
private float deltaT;
void Start()
{
stopTimer = false;
timerSlider.maxValue = gameTime;
timerSlider.value = gameTime;
}
// Update is called once per frame
public void Update()
{
deltaT = Time.time;
timerR();
}
public void timerR()
{
time1 = gameTime - deltaT;
Debug.Log(time1);
int minutes = Mathf.FloorToInt(time1 / 60);
int seconds = Mathf.FloorToInt(time1 - minutes * 60f);
string textTime = string.Format("{0:0}:{1:00}", minutes, seconds);
if (time1 <= 0)
{
stopTimer = true;
}
if (stopTimer == false)
{
timerText.text = textTime;
timerSlider.value = time1;
}
}
}
您可以使用Coroutine的强大功能和一些方便的 C# 类,如TimeSpan和Stopwatch ,类似于下面的代码。
using System;
using System.Collections;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.UI;
public class CountDown : MonoBehaviour
{
public Text text;
public int secounds = 5;
public int waitSecOnEachRound = 1;
readonly Stopwatch timer = new Stopwatch();
void Start()
{
StartCoroutine(CounDowntStarter());
}
IEnumerator CounDowntStarter()
{
TimeSpan timeStart = TimeSpan.FromSeconds(secounds);
while (true)
{
timer.Restart();
while (timer.Elapsed.TotalSeconds <= secounds)
{
yield return new WaitForSeconds(0.01f);
timeStart = TimeSpan.FromSeconds(secounds - Math.Floor(timer.Elapsed.TotalSeconds));
text.text = string.Format("{0:00} : {1:00}", timeStart.Minutes, timeStart.Seconds);
}
yield return new WaitForSeconds(waitSecOnEachRound);
}
}
}
在这个 web 中,您有一个简单的计时器: https://answers.unity.com/questions/351420/simple-timer-1.html这是我的示例代码:
float actualtime=0; #Time in the coundownt that we have now
public float maxtime=5;
float actualtimedelta=0;
string texTime
void Update()
{
actualtime=Time.deltaTime-actualtimedelta
if(actualtime>=5)
{
actualtimedelta=Time.deltatime
textTime ="00:00";
}
else
{
actualtime= maxtime-actualtime;
int seconds= Mathf.FloorToInt(actualtime);
int miliseconds=Mathf.FloorToInt((actualtime -seconds)*100)
texTime= string.Format("{0:0}:{1:00}", seconds, miliseconds);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.