From 2afbb545027568fccc85853e18af02a7c6b2929e Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Tue, 16 May 2023 16:03:51 +0800 Subject: *misc --- .../Assets/Scripts/Tools/ThreadSafeElapsedTime.cs | 87 ++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs (limited to 'WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs') 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; + +/// +/// 线程安全的时间流逝类 +/// 从游戏运行开始计时 +/// +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); + } + } + + /// + /// 自游戏启动以来的ticks + /// + /// + public static long GetElapsedTicksSinceStartUp() + { + #if UNITY_EDITOR + Start(); + Update(); + #endif + return _curRawElapsedTicks; + } + /// + /// 自游戏启动以来的seconds + /// + /// + public static float GetElapsedSecondsSinceStartUp() + { +#if UNITY_EDITOR + Start(); + Update(); +#endif + return _curRawElapsedSeconds; + } + + /// + /// 自游戏启动以来的miniseconds + /// + /// + public static int GetElapsedMiniSecondsSinceStartUp() + { +#if UNITY_EDITOR + Start(); + Update(); +#endif + return (int)(_curRawElapsedSeconds * 1000); + } +} -- cgit v1.1-26-g67d0