首页 > 解决方案 > 为一段时间创建一个类/方法(启动、重置、停止、获取 istant、获取 timerun)

问题描述

我正在开发一款赛车游戏,并且正在研究比赛时间。

我尝试构建一个系统来启动具有各种选项的计时器实例。

我的小经历让我陷入了危机……有好心人愿意帮助我吗?

这是这样的想法:

public class Timer {


    public float counter;
    public bool reset; 
    public string runtime = "--:--:--";
    public string istant = "not istant";

    public void startTimer()
    {

        /* inupdatealternative: counter += Time.deltaTime; */

        if(reset == true)
        {
            counter = 0;
        }
        else
        {
            counter = Time.time;
        }

        var minutes = counter/60;               // divide guitime by sixty (minutes)
        var seconds = counter%60;               // euclidean division (seconds)
        var fraction = (counter * 100) % 100;   // get fraction of seconds
        runtime = string.Format ( "{0:00}:{1:00}:{2:000}", minutes, seconds, fraction);

        Debug.Log("in Start: "+runtime);

    }

    public void resetTimer()
    {
        reset = true;
    }

    public string getTimerRuntime()
    {
        return runtime;
    }

    public string getTimerIstant()
    {
        istant = runtime;
        return istant;
    }

}

在更新中,例如:

var lapTimer = new Timer(); // create a new timer
if(Lap < Pilot.pilotlap )
{
    lapTimer.startTimer();
    Lap++
}
else if(Lap==Pilot.pilotlap)
{
    timerLabel.text = lapTimer.getTimerIstant();
    lapTimer.resetTimer();
    lapTimer.startTimer();
}

在我的脑海中我确定有人已经处理过它......肯定会有一些东西可以管理时代并以各种方式返回价值:它存在吗?或者无论如何如何制作或建造这样的东西?

标签: c#classunity3dmethodstime

解决方案


有,它被称为Stopwatch,它是 C# 中用于使用精确计时器的类,它位于System.Diagnostics命名空间中。

使用您的Update()示例,您可以像这样使用它:

// Create a new stopwatch instance
// If the timer is used repeatedly, just instantiate one at start and re-use the same,
// to avoid garbage generation
Stopwatch lapTimer = new Stopwatch();

if(Lap < Pilot.pilotlap )
{
    lapTimer.Start();
    Lap++
}
else if(Lap==Pilot.pilotlap)
{
    lapTimer.Stop();
    // ElapsedMilliseconds returns exactly what it says, so you may need to format the value
    // before passing it to the timerLabel.text
    timerLabel.text = lapTimer.ElapsedMilliseconds.ToString();
    lapTimer.Reset();
    lapTimer.Start();
}

您可以在此处阅读有关该类(其方法、字段和属性)的信息:

秒表类文档


推荐阅读