summaryrefslogtreecommitdiff
path: root/WorldlineKeepers/Assets/Scripts/Tools/ThreadSafeElapsedTime.cs
blob: 50da91b5b15323f8150844f07363cfc3598d10c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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);
    }
}