2using System.Runtime.CompilerServices;
4#if !UNITY_2020_3_OR_NEWER
5using Stopwatch = System.Diagnostics.Stopwatch;
19 static double lastPingTime;
25 static double offsetMin =
double.MinValue;
26 static double offsetMax =
double.MaxValue;
29#if UNITY_2020_3_OR_NEWER
30 public static double localTime
32 [MethodImpl(MethodImplOptions.AggressiveInlining)]
33 get => Time.timeAsDouble;
39 static readonly Stopwatch stopwatch =
new Stopwatch();
41 public static double localTime => stopwatch.Elapsed.TotalSeconds;
58 [MethodImpl(MethodImplOptions.AggressiveInlining)]
59 get => localTime - _offset.Value;
71 public static double offset => _offset.Value;
74 public static double rtt => _rtt.Value;
85 [UnityEngine.RuntimeInitializeOnLoadMethod]
86 public static void ResetStatics()
93 offsetMin =
double.MinValue;
94 offsetMax =
double.MaxValue;
95#if !UNITY_2020_3_OR_NEWER
100 internal static void UpdateClient()
107 lastPingTime = localTime;
114 internal static void OnServerPing(NetworkConnectionToClient conn, NetworkPingMessage message)
117 NetworkPongMessage pongMessage =
new NetworkPongMessage
119 clientTime = message.clientTime,
120 serverTime = localTime
122 conn.Send(pongMessage, Channels.Unreliable);
128 internal static void OnClientPong(NetworkPongMessage message)
130 double now = localTime;
133 double newRtt = now - message.clientTime;
139 double newOffset = now - newRtt * 0.5f - message.serverTime;
141 double newOffsetMin = now - newRtt - message.serverTime;
142 double newOffsetMax = now - message.serverTime;
143 offsetMin = Math.Max(offsetMin, newOffsetMin);
144 offsetMax = Math.Min(offsetMax, newOffsetMax);
146 if (_offset.Value < offsetMin || _offset.Value > offsetMax)
150 _offset.Add(newOffset);
152 else if (newOffset >= offsetMin || newOffset <= offsetMax)
155 _offset.Add(newOffset);
NetworkClient with connection to server.
Synchronizes server time to clients.
static double offset
Clock difference in seconds between the client and the server. Always 0 on server.
static double rtt
Round trip time (in seconds) that it takes a message to go client->server->client.
static double rttVariance
Round trip time variance. The higher, the less accurate the rtt is.
static double timeStandardDeviation
Time standard deviation. The highe, the less accurate the time is.
static int PingWindowSize
Average out the last few results from Ping
static double rttStandardDeviation
Round trip time standard deviation. The higher, the less accurate the rtt is.
static double time
The time in seconds since the server started.
static double timeVariance
Time measurement variance. The higher, the less accurate the time is.
static float PingFrequency
Ping message frequency, used to calculate network time and RTT