c# - 为一段时间创建一个类/方法(启动、重置、停止、获取 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();
}
在我的脑海中我确定有人已经处理过它......肯定会有一些东西可以管理时代并以各种方式返回价值:它存在吗?或者无论如何如何制作或建造这样的东西?
解决方案
有,它被称为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();
}
您可以在此处阅读有关该类(其方法、字段和属性)的信息:
推荐阅读
- postgresql - 如何提取 JSONB 数组的元素?
- android - getZoom 和 getVisibleBounds 方法永远不会在@mapbox/react-native-mapbox-gl Android 中解析
- python - 在地图/过滤器中使用就地函数有缺点吗?
- html - 如何将药丸箭头定位在长文本的右中心?
- angular - 通过 ng build 构建 Angular 项目时找不到 angular.json 文件错误
- spring-mvc - 在 Spring Boot 中添加服务器端动态验证
- r - R:使用 agrep 和 data.table 进行模糊合并
- angular - Angular 6 zip 已弃用:不再支持 resultSelector,改为使用管道映射
- codeship - Codeship Pro on_fail 跨步
- javascript - 当单击列表中的 li 项目时,如何使用 jquery 将单击的项目附加到单独的 div 中,并将剩余的列表项目附加到不同的 div 标签中