[英]Unity C# Player going too fast with Rigidbody2D.AddForce
[英]c# timer is going too fast if set
我正在尝试使用Timer(使用https://www.geoffstratton.com/cnet-countdown-timer代码)实现简单的倒计时。 如果我运行一次计时器,它确实可以工作,但是如果我停止计时器,或者下一次我将其启动到00:00时,它将快2倍。 如果我停止并重新启动它,它的运行速度将提高3倍。
(我的解释可能不清楚,我做了一个gif来演示问题) https://media.giphy.com/media/fQr7sX6LNRECvQpCYP/giphy.gif
我是C#的新手,我通常会想办法,但我无法了解这里发生的情况。 我包括了计时器代码。 如果有人可以帮助我,那就太好了! 谢谢 !!!
private void btnStartTimer_Click(object sender, EventArgs e)
{
if (txtTimer.Text == "00:00")
{
MessageBox.Show("Please enter the time to start!", "Enter the Time", MessageBoxButtons.OK);
}
else
{
string[] totalSeconds = txtTimer.Text.Split(':');
int minutes = Convert.ToInt32(totalSeconds[0]);
int seconds = Convert.ToInt32(totalSeconds[1]);
timeLeft = (minutes * 60) + seconds;
btnStartTimer.Enabled = false;
btnCleartimer.Enabled = false;
txtTimer.ReadOnly = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
}
private void btnStopTimer_Click(object sender, EventArgs e)
{
timer1.Stop();
timeLeft = 0;
btnStartTimer.Enabled = true;
btnCleartimer.Enabled = true;
txtTimer.ReadOnly = false;
}
private void btnCleartimer_Click(object sender, EventArgs e)
{
txtTimer.Text = "00:00";
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timeLeft > 0)
{
timeLeft = timeLeft - 1;
// Display time remaining as mm:ss
var timespan = TimeSpan.FromSeconds(timeLeft);
txtTimer.Text = timespan.ToString(@"mm\:ss");
// Alternate method
//int secondsLeft = timeLeft % 60;
//int minutesLeft = timeLeft / 60;
}
else
{
timer1.Stop();
SystemSounds.Exclamation.Play();
MessageBox.Show("Time's up!", "Time has elapsed", MessageBoxButtons.OK);
}
}
您需要通过btnStopTimer_Click方法退订该事件:
timer1.Tick -= timer1_Tick;
每次启动计时器时,您都将事件添加到Count中。 结果,第一次调用时只有一个事件,第二次只有两个事件,依此类推。 结果,您首先需要等待一秒钟,然后再等待两个.....我建议您分别创建计时器,然后仅调用Start和Stop。 Alternativ,如果您不想在其他地方创建计时器,则用户Dmitry Korolev回答了一个不错的方法
timer1.Tick -= timer1_Tick;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.