我在Unity中使用了C#秒表类,但它只返回00:00:00(I used the C# Stopwatch Class in Unity, but it returns only 00:00:00)

编程入门 行业动态 更新时间:2024-10-24 19:28:15
我在Unity中使用了C#秒表类,但它只返回00:00:00(I used the C# Stopwatch Class in Unity, but it returns only 00:00:00)

我想测量并返回用户按Tab键和空格键之间经过的时间。 不幸的是,我的代码只返回00:00:00。 到目前为止这是我的代码。

using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; using System; using System.Diagnostics; using Debug=UnityEngine.Debug; public class timer : MonoBehaviour { public Stopwatch zeit; void Update () { zeit = new Stopwatch(); if (Input.GetKeyDown ("tab")) { zeit.Start(); } if (Input.GetKeyDown ("space")){ TimeSpan ts = zeit.Elapsed; zeit.Stop (); print(ts); zeit.Reset (); } } }


I want to measure and return the time that passes between the time a user presses the Tab & the Space Button. Unfortunately my Code only returns 00:00:00. This is my code so far.

using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; using System; using System.Diagnostics; using Debug=UnityEngine.Debug; public class timer : MonoBehaviour { public Stopwatch zeit; void Update () { zeit = new Stopwatch(); if (Input.GetKeyDown ("tab")) { zeit.Start(); } if (Input.GetKeyDown ("space")){ TimeSpan ts = zeit.Elapsed; zeit.Stop (); print(ts); zeit.Reset (); } } }


最满意答案

您在调用更新时重新创建秒表。 您可以在“构造函数”中正手初始化秒表。

public Stopwatch zeit = new StopWatch(); void Update () { if (Input.GetKeyDown ("tab")) { zeit.Start(); } if (Input.GetKeyDown ("space")){ TimeSpan ts = zeit.Elapsed; zeit.Stop (); print(ts); zeit.Reset (); } }

You are re-creating the stopwatch when calling update. You can initialize the stopwatch on forehand in the "constructor".

public Stopwatch zeit = new StopWatch(); void Update () { if (Input.GetKeyDown ("tab")) { zeit.Start(); } if (Input.GetKeyDown ("space")){ TimeSpan ts = zeit.Elapsed; zeit.Stop (); print(ts); zeit.Reset (); } }

更多推荐

本文发布于:2023-07-29 15:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317590.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我在   秒表   它只   使用了   Unity

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!