diff options
author | chai <215380520@qq.com> | 2023-05-16 16:03:51 +0800 |
---|---|---|
committer | chai <215380520@qq.com> | 2023-05-16 16:03:51 +0800 |
commit | 2afbb545027568fccc85853e18af02a7c6b2929e (patch) | |
tree | 3827873af133fe9f81041e4babbfd0d54a53f9d1 /WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs | |
parent | 88f739ea0f3440152082f34707e79328a71aabed (diff) |
*misc
Diffstat (limited to 'WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs')
-rw-r--r-- | WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs b/WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs new file mode 100644 index 0000000..50da91b --- /dev/null +++ b/WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs @@ -0,0 +1,87 @@ +using System; +using System.Diagnostics; + +/// <summary> +/// 线程安全的时间流逝类 +/// 从游戏运行开始计时 +/// </summary> +public static class ThreadSafeElapsedTime +{ + private static bool _isStart = false; + private static Stopwatch _stopwatch; + private static long _curRawElapsedTicks; + private static float _curRawElapsedSeconds; + + static private double ticks2seconds = 1 / (double) TimeSpan.TicksPerSecond; + + + //必须在启动后调用 + public static void Start() + { + if (!_isStart) + { + _isStart = true; + _stopwatch = new Stopwatch(); + _stopwatch.Start(); + _curRawElapsedTicks = 0; + _curRawElapsedSeconds = 0; + } + } + + public static void Stop() + { + if (_isStart) + { + _isStart = false; + _stopwatch.Stop(); + } + } + + public static void Update() + { + if (_isStart) + { + _curRawElapsedTicks = _stopwatch.ElapsedTicks; + //_curRawElapsedSeconds = (int)(_curRawElapsedTicks / System.TimeSpan.TicksPerSecond); + _curRawElapsedSeconds = (float)(((double) _curRawElapsedTicks ) * ticks2seconds); + } + } + + /// <summary> + /// 自游戏启动以来的ticks + /// </summary> + /// <returns></returns> + public static long GetElapsedTicksSinceStartUp() + { + #if UNITY_EDITOR + Start(); + Update(); + #endif + return _curRawElapsedTicks; + } + /// <summary> + /// 自游戏启动以来的seconds + /// </summary> + /// <returns></returns> + public static float GetElapsedSecondsSinceStartUp() + { +#if UNITY_EDITOR + Start(); + Update(); +#endif + return _curRawElapsedSeconds; + } + + /// <summary> + /// 自游戏启动以来的miniseconds + /// </summary> + /// <returns></returns> + public static int GetElapsedMiniSecondsSinceStartUp() + { +#if UNITY_EDITOR + Start(); + Update(); +#endif + return (int)(_curRawElapsedSeconds * 1000); + } +} |