NetworkClient.cs 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Mirror.RemoteCalls;
  5. using UnityEngine;
  6. namespace Mirror
  7. {
  8. public enum ConnectState
  9. {
  10. None,
  11. // connecting between Connect() and OnTransportConnected()
  12. Connecting,
  13. Connected,
  14. // disconnecting between Disconnect() and OnTransportDisconnected()
  15. Disconnecting,
  16. Disconnected
  17. }
  18. /// <summary>NetworkClient with connection to server.</summary>
  19. public static partial class NetworkClient
  20. {
  21. // time & value snapshot interpolation are separate.
  22. // -> time is interpolated globally on NetworkClient / NetworkConnection
  23. // -> value is interpolated per-component, i.e. NetworkTransform.
  24. // however, both need to be on the same send interval.
  25. //
  26. // additionally, server & client need to use the same send interval.
  27. // otherwise it's too easy to accidentally cause interpolation issues if
  28. // a component sends with client.interval but interpolates with
  29. // server.interval, etc.
  30. public static int sendRate => NetworkServer.sendRate;
  31. public static float sendInterval => sendRate < int.MaxValue ? 1f / sendRate : 0; // for 30 Hz, that's 33ms
  32. static double lastSendTime;
  33. // For security, it is recommended to disconnect a player if a networked
  34. // action triggers an exception\nThis could prevent components being
  35. // accessed in an undefined state, which may be an attack vector for
  36. // exploits.
  37. //
  38. // However, some games may want to allow exceptions in order to not
  39. // interrupt the player's experience.
  40. public static bool exceptionsDisconnect = true; // security by default
  41. // message handlers by messageId
  42. internal static readonly Dictionary<ushort, NetworkMessageDelegate> handlers =
  43. new Dictionary<ushort, NetworkMessageDelegate>();
  44. /// <summary>All spawned NetworkIdentities by netId.</summary>
  45. // client sees OBSERVED spawned ones.
  46. public static readonly Dictionary<uint, NetworkIdentity> spawned =
  47. new Dictionary<uint, NetworkIdentity>();
  48. /// <summary>Client's NetworkConnection to server.</summary>
  49. public static NetworkConnection connection { get; internal set; }
  50. /// <summary>True if client is ready (= joined world).</summary>
  51. // TODO redundant state. point it to .connection.isReady instead (& test)
  52. // TODO OR remove NetworkConnection.isReady? unless it's used on server
  53. //
  54. // TODO maybe ClientState.Connected/Ready/AddedPlayer/etc.?
  55. // way better for security if we can check states in callbacks
  56. public static bool ready;
  57. /// <summary>NetworkIdentity of the localPlayer </summary>
  58. public static NetworkIdentity localPlayer { get; internal set; }
  59. // NetworkClient state
  60. internal static ConnectState connectState = ConnectState.None;
  61. /// <summary>active is true while a client is connecting/connected either as standalone or as host client.</summary>
  62. // (= while the network is active)
  63. public static bool active => connectState == ConnectState.Connecting ||
  64. connectState == ConnectState.Connected;
  65. /// <summary>active is true while the client is connected in host mode.</summary>
  66. // naming consistent with NetworkServer.activeHost.
  67. public static bool activeHost => connection is LocalConnectionToServer;
  68. /// <summary>Check if client is connecting (before connected).</summary>
  69. public static bool isConnecting => connectState == ConnectState.Connecting;
  70. /// <summary>Check if client is connected (after connecting).</summary>
  71. public static bool isConnected => connectState == ConnectState.Connected;
  72. // OnConnected / OnDisconnected used to be NetworkMessages that were
  73. // invoked. this introduced a bug where external clients could send
  74. // Connected/Disconnected messages over the network causing undefined
  75. // behaviour.
  76. // => public so that custom NetworkManagers can hook into it
  77. public static Action OnConnectedEvent;
  78. public static Action OnDisconnectedEvent;
  79. public static Action<TransportError, string> OnErrorEvent;
  80. /// <summary>Registered spawnable prefabs by assetId.</summary>
  81. public static readonly Dictionary<uint, GameObject> prefabs =
  82. new Dictionary<uint, GameObject>();
  83. // custom spawn / unspawn handlers by assetId.
  84. // useful to support prefab pooling etc.:
  85. // https://mirror-networking.gitbook.io/docs/guides/gameobjects/custom-spawnfunctions
  86. internal static readonly Dictionary<uint, SpawnHandlerDelegate> spawnHandlers =
  87. new Dictionary<uint, SpawnHandlerDelegate>();
  88. internal static readonly Dictionary<uint, UnSpawnDelegate> unspawnHandlers =
  89. new Dictionary<uint, UnSpawnDelegate>();
  90. // spawning
  91. // internal for tests
  92. internal static bool isSpawnFinished;
  93. // Disabled scene objects that can be spawned again, by sceneId.
  94. internal static readonly Dictionary<ulong, NetworkIdentity> spawnableObjects =
  95. new Dictionary<ulong, NetworkIdentity>();
  96. internal static Unbatcher unbatcher = new Unbatcher();
  97. // interest management component (optional)
  98. // only needed for SetHostVisibility
  99. public static InterestManagementBase aoi;
  100. // scene loading
  101. public static bool isLoadingScene;
  102. // connection quality
  103. // this is set by a virtual function in NetworkManager,
  104. // which allows users to overwrite it with their own estimations.
  105. public static ConnectionQuality connectionQuality = ConnectionQuality.ESTIMATING;
  106. public static ConnectionQuality lastConnectionQuality = ConnectionQuality.ESTIMATING;
  107. public static ConnectionQualityMethod connectionQualityMethod = ConnectionQualityMethod.Simple;
  108. public static float connectionQualityInterval = 3;
  109. static double lastConnectionQualityUpdate;
  110. /// <summary>
  111. /// Invoked when connection quality changes.
  112. /// <para>First argument is the old quality, second argument is the new quality.</para>
  113. /// </summary>
  114. public static event Action<ConnectionQuality, ConnectionQuality> onConnectionQualityChanged;
  115. // initialization //////////////////////////////////////////////////////
  116. static void AddTransportHandlers()
  117. {
  118. // community Transports may forget to call OnDisconnected.
  119. // which could cause handlers to be added twice with +=.
  120. // ensure we always clear the old ones first.
  121. // fixes: https://github.com/vis2k/Mirror/issues/3152
  122. RemoveTransportHandlers();
  123. // += so that other systems can also hook into it (i.e. statistics)
  124. Transport.active.OnClientConnected += OnTransportConnected;
  125. Transport.active.OnClientDataReceived += OnTransportData;
  126. Transport.active.OnClientDisconnected += OnTransportDisconnected;
  127. Transport.active.OnClientError += OnTransportError;
  128. }
  129. static void RemoveTransportHandlers()
  130. {
  131. // -= so that other systems can also hook into it (i.e. statistics)
  132. Transport.active.OnClientConnected -= OnTransportConnected;
  133. Transport.active.OnClientDataReceived -= OnTransportData;
  134. Transport.active.OnClientDisconnected -= OnTransportDisconnected;
  135. Transport.active.OnClientError -= OnTransportError;
  136. }
  137. // connect /////////////////////////////////////////////////////////////
  138. // initialize is called before every connect
  139. static void Initialize(bool hostMode)
  140. {
  141. // safety: ensure Weaving succeded.
  142. // if it silently failed, we would get lots of 'writer not found'
  143. // and other random errors at runtime instead. this is cleaner.
  144. if (!WeaverFuse.Weaved())
  145. {
  146. // if it failed, throw an exception to early exit all Connect calls.
  147. throw new Exception("NetworkClient won't start because Weaving failed or didn't run.");
  148. }
  149. // Debug.Log($"Client Connect: {address}");
  150. Debug.Assert(Transport.active != null, "There was no active transport when calling NetworkClient.Connect, If you are calling Connect manually then make sure to set 'Transport.active' first");
  151. // reset unbatcher in case any batches from last session remain.
  152. // need to do this in Initialize() so it runs for the host as well.
  153. // fixes host mode scene transition receiving data from previous scene.
  154. // credits: BigBoxVR
  155. unbatcher = new Unbatcher();
  156. // reset time interpolation on every new connect.
  157. // ensures last sessions' state is cleared before starting again.
  158. InitTimeInterpolation();
  159. RegisterMessageHandlers(hostMode);
  160. Transport.active.enabled = true;
  161. }
  162. /// <summary>Connect client to a NetworkServer by address.</summary>
  163. public static void Connect(string address)
  164. {
  165. Initialize(false);
  166. AddTransportHandlers();
  167. connectState = ConnectState.Connecting;
  168. Transport.active.ClientConnect(address);
  169. connection = new NetworkConnectionToServer();
  170. }
  171. /// <summary>Connect client to a NetworkServer by Uri.</summary>
  172. public static void Connect(Uri uri)
  173. {
  174. Initialize(false);
  175. AddTransportHandlers();
  176. connectState = ConnectState.Connecting;
  177. Transport.active.ClientConnect(uri);
  178. connection = new NetworkConnectionToServer();
  179. }
  180. // TODO why are there two connect host methods?
  181. // called from NetworkManager.FinishStartHost()
  182. public static void ConnectHost()
  183. {
  184. Initialize(true);
  185. connectState = ConnectState.Connected;
  186. HostMode.SetupConnections();
  187. }
  188. // disconnect //////////////////////////////////////////////////////////
  189. /// <summary>Disconnect from server.</summary>
  190. public static void Disconnect()
  191. {
  192. // only if connected or connecting.
  193. // don't disconnect() again if already in the process of
  194. // disconnecting or fully disconnected.
  195. if (connectState != ConnectState.Connecting &&
  196. connectState != ConnectState.Connected)
  197. return;
  198. // we are disconnecting until OnTransportDisconnected is called.
  199. // setting state to Disconnected would stop OnTransportDisconnected
  200. // from calling cleanup code because it would think we are already
  201. // disconnected fully.
  202. // TODO move to 'cleanup' code below if safe
  203. connectState = ConnectState.Disconnecting;
  204. ready = false;
  205. // call Disconnect on the NetworkConnection
  206. connection?.Disconnect();
  207. // IMPORTANT: do NOT clear connection here yet.
  208. // we still need it in OnTransportDisconnected for callbacks.
  209. // connection = null;
  210. }
  211. // transport events ////////////////////////////////////////////////////
  212. // called by Transport
  213. static void OnTransportConnected()
  214. {
  215. if (connection != null)
  216. {
  217. // reset network time stats
  218. NetworkTime.ResetStatics();
  219. // the handler may want to send messages to the client
  220. // thus we should set the connected state before calling the handler
  221. connectState = ConnectState.Connected;
  222. NetworkTime.UpdateClient();
  223. OnConnectedEvent?.Invoke();
  224. }
  225. else Debug.LogError("Skipped Connect message handling because connection is null.");
  226. }
  227. // helper function
  228. static bool UnpackAndInvoke(NetworkReader reader, int channelId)
  229. {
  230. if (NetworkMessages.UnpackId(reader, out ushort msgType))
  231. {
  232. // try to invoke the handler for that message
  233. if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler))
  234. {
  235. handler.Invoke(connection, reader, channelId);
  236. // message handler may disconnect client, making connection = null
  237. // therefore must check for null to avoid NRE.
  238. if (connection != null)
  239. connection.lastMessageTime = Time.time;
  240. return true;
  241. }
  242. else
  243. {
  244. // message in a batch are NOT length prefixed to save bandwidth.
  245. // every message needs to be handled and read until the end.
  246. // otherwise it would overlap into the next message.
  247. // => need to warn and disconnect to avoid undefined behaviour.
  248. // => WARNING, not error. can happen if attacker sends random data.
  249. Debug.LogWarning($"Unknown message id: {msgType}. This can happen if no handler was registered for this message.");
  250. // simply return false. caller is responsible for disconnecting.
  251. //connection.Disconnect();
  252. return false;
  253. }
  254. }
  255. else
  256. {
  257. // => WARNING, not error. can happen if attacker sends random data.
  258. Debug.LogWarning("Invalid message header.");
  259. // simply return false. caller is responsible for disconnecting.
  260. //connection.Disconnect();
  261. return false;
  262. }
  263. }
  264. // called by Transport
  265. internal static void OnTransportData(ArraySegment<byte> data, int channelId)
  266. {
  267. if (connection != null)
  268. {
  269. // server might batch multiple messages into one packet.
  270. // feed it to the Unbatcher.
  271. // NOTE: we don't need to associate a channelId because we
  272. // always process all messages in the batch.
  273. if (!unbatcher.AddBatch(data))
  274. {
  275. Debug.LogWarning($"NetworkClient: failed to add batch, disconnecting.");
  276. connection.Disconnect();
  277. return;
  278. }
  279. // process all messages in the batch.
  280. // only while NOT loading a scene.
  281. // if we get a scene change message, then we need to stop
  282. // processing. otherwise we might apply them to the old scene.
  283. // => fixes https://github.com/vis2k/Mirror/issues/2651
  284. //
  285. // NOTE: is scene starts loading, then the rest of the batch
  286. // would only be processed when OnTransportData is called
  287. // the next time.
  288. // => consider moving processing to NetworkEarlyUpdate.
  289. while (!isLoadingScene &&
  290. unbatcher.GetNextMessage(out ArraySegment<byte> message, out double remoteTimestamp))
  291. {
  292. using (NetworkReaderPooled reader = NetworkReaderPool.Get(message))
  293. {
  294. // enough to read at least header size?
  295. if (reader.Remaining >= NetworkMessages.IdSize)
  296. {
  297. // make remoteTimeStamp available to the user
  298. connection.remoteTimeStamp = remoteTimestamp;
  299. // handle message
  300. if (!UnpackAndInvoke(reader, channelId))
  301. {
  302. // warn, disconnect and return if failed
  303. // -> warning because attackers might send random data
  304. // -> messages in a batch aren't length prefixed.
  305. // failing to read one would cause undefined
  306. // behaviour for every message afterwards.
  307. // so we need to disconnect.
  308. // -> return to avoid the below unbatches.count error.
  309. // we already disconnected and handled it.
  310. Debug.LogWarning($"NetworkClient: failed to unpack and invoke message. Disconnecting.");
  311. connection.Disconnect();
  312. return;
  313. }
  314. }
  315. // otherwise disconnect
  316. else
  317. {
  318. // WARNING, not error. can happen if attacker sends random data.
  319. Debug.LogWarning($"NetworkClient: received Message was too short (messages should start with message id)");
  320. connection.Disconnect();
  321. return;
  322. }
  323. }
  324. }
  325. // if we weren't interrupted by a scene change,
  326. // then all batched messages should have been processed now.
  327. // if not, we need to log an error to avoid debugging hell.
  328. // otherwise batches would silently grow.
  329. // we need to log an error to avoid debugging hell.
  330. //
  331. // EXAMPLE: https://github.com/vis2k/Mirror/issues/2882
  332. // -> UnpackAndInvoke silently returned because no handler for id
  333. // -> Reader would never be read past the end
  334. // -> Batch would never be retired because end is never reached
  335. //
  336. // NOTE: prefixing every message in a batch with a length would
  337. // avoid ever not reading to the end. for extra bandwidth.
  338. //
  339. // IMPORTANT: always keep this check to detect memory leaks.
  340. // this took half a day to debug last time.
  341. if (!isLoadingScene && unbatcher.BatchesCount > 0)
  342. {
  343. Debug.LogError($"Still had {unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end.");
  344. }
  345. }
  346. else Debug.LogError("Skipped Data message handling because connection is null.");
  347. }
  348. // called by Transport
  349. // IMPORTANT: often times when disconnecting, we call this from Mirror
  350. // too because we want to remove the connection and handle
  351. // the disconnect immediately.
  352. // => which is fine as long as we guarantee it only runs once
  353. // => which we do by setting the state to Disconnected!
  354. internal static void OnTransportDisconnected()
  355. {
  356. // StopClient called from user code triggers Disconnected event
  357. // from transport which calls StopClient again, so check here
  358. // and short circuit running the Shutdown process twice.
  359. if (connectState == ConnectState.Disconnected) return;
  360. // Raise the event before changing ConnectState
  361. // because 'active' depends on this during shutdown
  362. //
  363. // previously OnDisconnected was only invoked if connection != null.
  364. // however, if DNS resolve fails in Transport.Connect(),
  365. // OnDisconnected would never be called because 'connection' is only
  366. // created after the Transport.Connect() call.
  367. // fixes: https://github.com/MirrorNetworking/Mirror/issues/3365
  368. OnDisconnectedEvent?.Invoke();
  369. connectState = ConnectState.Disconnected;
  370. ready = false;
  371. snapshots.Clear();
  372. localTimeline = 0;
  373. // now that everything was handled, clear the connection.
  374. // previously this was done in Disconnect() already, but we still
  375. // need it for the above OnDisconnectedEvent.
  376. connection = null;
  377. // transport handlers are only added when connecting.
  378. // so only remove when actually disconnecting.
  379. RemoveTransportHandlers();
  380. }
  381. // transport errors are forwarded to high level
  382. static void OnTransportError(TransportError error, string reason)
  383. {
  384. // transport errors will happen. logging a warning is enough.
  385. // make sure the user does not panic.
  386. Debug.LogWarning($"Client Transport Error: {error}: {reason}. This is fine.");
  387. OnErrorEvent?.Invoke(error, reason);
  388. }
  389. // send ////////////////////////////////////////////////////////////////
  390. /// <summary>Send a NetworkMessage to the server over the given channel.</summary>
  391. public static void Send<T>(T message, int channelId = Channels.Reliable)
  392. where T : struct, NetworkMessage
  393. {
  394. if (connection != null)
  395. {
  396. if (connectState == ConnectState.Connected)
  397. {
  398. connection.Send(message, channelId);
  399. }
  400. else Debug.LogError("NetworkClient Send when not connected to a server");
  401. }
  402. else Debug.LogError("NetworkClient Send with no connection");
  403. }
  404. // message handlers ////////////////////////////////////////////////////
  405. internal static void RegisterMessageHandlers(bool hostMode)
  406. {
  407. // host mode client / remote client react to some messages differently.
  408. // but we still need to add handlers for all of them to avoid
  409. // 'message id not found' errors.
  410. if (hostMode)
  411. {
  412. RegisterHandler<ObjectDestroyMessage>(OnHostClientObjectDestroy);
  413. RegisterHandler<ObjectHideMessage>(OnHostClientObjectHide);
  414. RegisterHandler<NetworkPongMessage>(_ => { }, false);
  415. RegisterHandler<SpawnMessage>(OnHostClientSpawn);
  416. // host mode doesn't need spawning
  417. RegisterHandler<ObjectSpawnStartedMessage>(_ => { });
  418. // host mode doesn't need spawning
  419. RegisterHandler<ObjectSpawnFinishedMessage>(_ => { });
  420. // host mode doesn't need state updates
  421. RegisterHandler<EntityStateMessage>(_ => { });
  422. }
  423. else
  424. {
  425. RegisterHandler<ObjectDestroyMessage>(OnObjectDestroy);
  426. RegisterHandler<ObjectHideMessage>(OnObjectHide);
  427. RegisterHandler<NetworkPongMessage>(NetworkTime.OnClientPong, false);
  428. RegisterHandler<NetworkPingMessage>(NetworkTime.OnClientPing, false);
  429. RegisterHandler<SpawnMessage>(OnSpawn);
  430. RegisterHandler<ObjectSpawnStartedMessage>(OnObjectSpawnStarted);
  431. RegisterHandler<ObjectSpawnFinishedMessage>(OnObjectSpawnFinished);
  432. RegisterHandler<EntityStateMessage>(OnEntityStateMessage);
  433. }
  434. // These handlers are the same for host and remote clients
  435. RegisterHandler<TimeSnapshotMessage>(OnTimeSnapshotMessage);
  436. RegisterHandler<ChangeOwnerMessage>(OnChangeOwner);
  437. RegisterHandler<RpcMessage>(OnRPCMessage);
  438. }
  439. /// <summary>Register a handler for a message type T. Most should require authentication.</summary>
  440. public static void RegisterHandler<T>(Action<T> handler, bool requireAuthentication = true)
  441. where T : struct, NetworkMessage
  442. {
  443. ushort msgType = NetworkMessageId<T>.Id;
  444. if (handlers.ContainsKey(msgType))
  445. {
  446. Debug.LogWarning($"NetworkClient.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
  447. }
  448. // register Id <> Type in lookup for debugging.
  449. NetworkMessages.Lookup[msgType] = typeof(T);
  450. // we use the same WrapHandler function for server and client.
  451. // so let's wrap it to ignore the NetworkConnection parameter.
  452. // it's not needed on client. it's always NetworkClient.connection.
  453. void HandlerWrapped(NetworkConnection _, T value) => handler(value);
  454. handlers[msgType] = NetworkMessages.WrapHandler((Action<NetworkConnection, T>)HandlerWrapped, requireAuthentication, exceptionsDisconnect);
  455. }
  456. /// <summary>Replace a handler for a particular message type. Should require authentication by default.</summary>
  457. // RegisterHandler throws a warning (as it should) if a handler is assigned twice
  458. // Use of ReplaceHandler makes it clear the user intended to replace the handler
  459. public static void ReplaceHandler<T>(Action<NetworkConnection, T> handler, bool requireAuthentication = true)
  460. where T : struct, NetworkMessage
  461. {
  462. ushort msgType = NetworkMessageId<T>.Id;
  463. handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication, exceptionsDisconnect);
  464. }
  465. /// <summary>Replace a handler for a particular message type. Should require authentication by default.</summary>
  466. // RegisterHandler throws a warning (as it should) if a handler is assigned twice
  467. // Use of ReplaceHandler makes it clear the user intended to replace the handler
  468. public static void ReplaceHandler<T>(Action<T> handler, bool requireAuthentication = true)
  469. where T : struct, NetworkMessage
  470. {
  471. ReplaceHandler((NetworkConnection _, T value) => { handler(value); }, requireAuthentication);
  472. }
  473. /// <summary>Unregister a message handler of type T.</summary>
  474. public static bool UnregisterHandler<T>()
  475. where T : struct, NetworkMessage
  476. {
  477. // use int to minimize collisions
  478. ushort msgType = NetworkMessageId<T>.Id;
  479. return handlers.Remove(msgType);
  480. }
  481. // spawnable prefabs ///////////////////////////////////////////////////
  482. /// <summary>Find the registered prefab for this asset id.</summary>
  483. // Useful for debuggers
  484. public static bool GetPrefab(uint assetId, out GameObject prefab)
  485. {
  486. prefab = null;
  487. return assetId != 0 &&
  488. prefabs.TryGetValue(assetId, out prefab) &&
  489. prefab != null;
  490. }
  491. /// <summary>Validates Prefab then adds it to prefabs dictionary.</summary>
  492. static void RegisterPrefabIdentity(NetworkIdentity prefab)
  493. {
  494. if (prefab.assetId == 0)
  495. {
  496. Debug.LogError($"Can not Register '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead");
  497. return;
  498. }
  499. if (prefab.sceneId != 0)
  500. {
  501. Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene.");
  502. return;
  503. }
  504. // disallow child NetworkIdentities.
  505. // TODO likely not necessary anymore due to the new check in
  506. // NetworkIdentity.OnValidate.
  507. NetworkIdentity[] identities = prefab.GetComponentsInChildren<NetworkIdentity>();
  508. if (identities.Length > 1)
  509. {
  510. Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object.");
  511. }
  512. if (prefabs.ContainsKey(prefab.assetId))
  513. {
  514. GameObject existingPrefab = prefabs[prefab.assetId];
  515. Debug.LogWarning($"Replacing existing prefab with assetId '{prefab.assetId}'. Old prefab '{existingPrefab.name}', New prefab '{prefab.name}'");
  516. }
  517. if (spawnHandlers.ContainsKey(prefab.assetId) || unspawnHandlers.ContainsKey(prefab.assetId))
  518. {
  519. Debug.LogWarning($"Adding prefab '{prefab.name}' with assetId '{prefab.assetId}' when spawnHandlers with same assetId already exists. If you want to use custom spawn handling, then remove the prefab from NetworkManager's registered prefabs first.");
  520. }
  521. // Debug.Log($"Registering prefab '{prefab.name}' as asset:{prefab.assetId}");
  522. prefabs[prefab.assetId] = prefab.gameObject;
  523. }
  524. /// <summary>Register spawnable prefab with custom assetId.</summary>
  525. // Note: newAssetId can not be set on GameObjects that already have an assetId
  526. // Note: registering with assetId is useful for assetbundles etc. a lot
  527. // of people use this.
  528. public static void RegisterPrefab(GameObject prefab, uint newAssetId)
  529. {
  530. if (prefab == null)
  531. {
  532. Debug.LogError("Could not register prefab because it was null");
  533. return;
  534. }
  535. if (newAssetId == 0)
  536. {
  537. Debug.LogError($"Could not register '{prefab.name}' with new assetId because the new assetId was empty");
  538. return;
  539. }
  540. if (!prefab.TryGetComponent(out NetworkIdentity identity))
  541. {
  542. Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component");
  543. return;
  544. }
  545. if (identity.assetId != 0 && identity.assetId != newAssetId)
  546. {
  547. Debug.LogError($"Could not register '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}");
  548. return;
  549. }
  550. identity.assetId = newAssetId;
  551. RegisterPrefabIdentity(identity);
  552. }
  553. /// <summary>Register spawnable prefab.</summary>
  554. public static void RegisterPrefab(GameObject prefab)
  555. {
  556. if (prefab == null)
  557. {
  558. Debug.LogError("Could not register prefab because it was null");
  559. return;
  560. }
  561. if (!prefab.TryGetComponent(out NetworkIdentity identity))
  562. {
  563. Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component");
  564. return;
  565. }
  566. RegisterPrefabIdentity(identity);
  567. }
  568. /// <summary>Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers.</summary>
  569. // Note: newAssetId can not be set on GameObjects that already have an assetId
  570. // Note: registering with assetId is useful for assetbundles etc. a lot
  571. // of people use this.
  572. // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate?
  573. public static void RegisterPrefab(GameObject prefab, uint newAssetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
  574. {
  575. // We need this check here because we don't want a null handler in the lambda expression below
  576. if (spawnHandler == null)
  577. {
  578. Debug.LogError($"Can not Register null SpawnHandler for {newAssetId}");
  579. return;
  580. }
  581. RegisterPrefab(prefab, newAssetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler);
  582. }
  583. /// <summary>Register a spawnable prefab with custom spawn/unspawn handlers.</summary>
  584. // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate?
  585. public static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
  586. {
  587. if (prefab == null)
  588. {
  589. Debug.LogError("Could not register handler for prefab because the prefab was null");
  590. return;
  591. }
  592. if (!prefab.TryGetComponent(out NetworkIdentity identity))
  593. {
  594. Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component");
  595. return;
  596. }
  597. if (identity.sceneId != 0)
  598. {
  599. Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene.");
  600. return;
  601. }
  602. if (identity.assetId == 0)
  603. {
  604. Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead");
  605. return;
  606. }
  607. // We need this check here because we don't want a null handler in the lambda expression below
  608. if (spawnHandler == null)
  609. {
  610. Debug.LogError($"Can not Register null SpawnHandler for {identity.assetId}");
  611. return;
  612. }
  613. RegisterPrefab(prefab, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler);
  614. }
  615. /// <summary>Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers.</summary>
  616. // Note: newAssetId can not be set on GameObjects that already have an assetId
  617. // Note: registering with assetId is useful for assetbundles etc. a lot
  618. // of people use this.
  619. // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate?
  620. public static void RegisterPrefab(GameObject prefab, uint newAssetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
  621. {
  622. if (newAssetId == 0)
  623. {
  624. Debug.LogError($"Could not register handler for '{prefab.name}' with new assetId because the new assetId was empty");
  625. return;
  626. }
  627. if (prefab == null)
  628. {
  629. Debug.LogError("Could not register handler for prefab because the prefab was null");
  630. return;
  631. }
  632. if (!prefab.TryGetComponent(out NetworkIdentity identity))
  633. {
  634. Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component");
  635. return;
  636. }
  637. if (identity.assetId != 0 && identity.assetId != newAssetId)
  638. {
  639. Debug.LogError($"Could not register Handler for '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}");
  640. return;
  641. }
  642. if (identity.sceneId != 0)
  643. {
  644. Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene.");
  645. return;
  646. }
  647. identity.assetId = newAssetId;
  648. uint assetId = identity.assetId;
  649. if (spawnHandler == null)
  650. {
  651. Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
  652. return;
  653. }
  654. if (unspawnHandler == null)
  655. {
  656. Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}");
  657. return;
  658. }
  659. if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId))
  660. {
  661. Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'");
  662. }
  663. if (prefabs.ContainsKey(assetId))
  664. {
  665. // this is error because SpawnPrefab checks prefabs before handler
  666. Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler");
  667. }
  668. NetworkIdentity[] identities = prefab.GetComponentsInChildren<NetworkIdentity>();
  669. if (identities.Length > 1)
  670. {
  671. Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object.");
  672. }
  673. //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}");
  674. spawnHandlers[assetId] = spawnHandler;
  675. unspawnHandlers[assetId] = unspawnHandler;
  676. }
  677. /// <summary>Register a spawnable prefab with custom spawn/unspawn handlers.</summary>
  678. // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate?
  679. public static void RegisterPrefab(GameObject prefab, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
  680. {
  681. if (prefab == null)
  682. {
  683. Debug.LogError("Could not register handler for prefab because the prefab was null");
  684. return;
  685. }
  686. if (!prefab.TryGetComponent(out NetworkIdentity identity))
  687. {
  688. Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component");
  689. return;
  690. }
  691. if (identity.sceneId != 0)
  692. {
  693. Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene.");
  694. return;
  695. }
  696. uint assetId = identity.assetId;
  697. if (assetId == 0)
  698. {
  699. Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead");
  700. return;
  701. }
  702. if (spawnHandler == null)
  703. {
  704. Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
  705. return;
  706. }
  707. if (unspawnHandler == null)
  708. {
  709. Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}");
  710. return;
  711. }
  712. if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId))
  713. {
  714. Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'");
  715. }
  716. if (prefabs.ContainsKey(assetId))
  717. {
  718. // this is error because SpawnPrefab checks prefabs before handler
  719. Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler");
  720. }
  721. NetworkIdentity[] identities = prefab.GetComponentsInChildren<NetworkIdentity>();
  722. if (identities.Length > 1)
  723. {
  724. Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object.");
  725. }
  726. //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}");
  727. spawnHandlers[assetId] = spawnHandler;
  728. unspawnHandlers[assetId] = unspawnHandler;
  729. }
  730. /// <summary>Removes a registered spawn prefab that was setup with NetworkClient.RegisterPrefab.</summary>
  731. public static void UnregisterPrefab(GameObject prefab)
  732. {
  733. if (prefab == null)
  734. {
  735. Debug.LogError("Could not unregister prefab because it was null");
  736. return;
  737. }
  738. if (!prefab.TryGetComponent(out NetworkIdentity identity))
  739. {
  740. Debug.LogError($"Could not unregister '{prefab.name}' since it contains no NetworkIdentity component");
  741. return;
  742. }
  743. uint assetId = identity.assetId;
  744. prefabs.Remove(assetId);
  745. spawnHandlers.Remove(assetId);
  746. unspawnHandlers.Remove(assetId);
  747. }
  748. // spawn handlers //////////////////////////////////////////////////////
  749. /// <summary>This is an advanced spawning function that registers a custom assetId with the spawning system.</summary>
  750. // This can be used to register custom spawning methods for an assetId -
  751. // instead of the usual method of registering spawning methods for a
  752. // prefab. This should be used when no prefab exists for the spawned
  753. // objects - such as when they are constructed dynamically at runtime
  754. // from configuration data.
  755. public static void RegisterSpawnHandler(uint assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
  756. {
  757. // We need this check here because we don't want a null handler in the lambda expression below
  758. if (spawnHandler == null)
  759. {
  760. Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
  761. return;
  762. }
  763. RegisterSpawnHandler(assetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler);
  764. }
  765. /// <summary>This is an advanced spawning function that registers a custom assetId with the spawning system.</summary>
  766. // This can be used to register custom spawning methods for an assetId -
  767. // instead of the usual method of registering spawning methods for a
  768. // prefab. This should be used when no prefab exists for the spawned
  769. // objects - such as when they are constructed dynamically at runtime
  770. // from configuration data.
  771. public static void RegisterSpawnHandler(uint assetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
  772. {
  773. if (spawnHandler == null)
  774. {
  775. Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
  776. return;
  777. }
  778. if (unspawnHandler == null)
  779. {
  780. Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}");
  781. return;
  782. }
  783. if (assetId == 0)
  784. {
  785. Debug.LogError("Can not Register SpawnHandler for empty assetId");
  786. return;
  787. }
  788. if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId))
  789. {
  790. Debug.LogWarning($"Replacing existing spawnHandlers for {assetId}");
  791. }
  792. if (prefabs.ContainsKey(assetId))
  793. {
  794. // this is error because SpawnPrefab checks prefabs before handler
  795. Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}'");
  796. }
  797. // Debug.Log("RegisterSpawnHandler asset {assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}");
  798. spawnHandlers[assetId] = spawnHandler;
  799. unspawnHandlers[assetId] = unspawnHandler;
  800. }
  801. /// <summary> Removes a registered spawn handler function that was registered with NetworkClient.RegisterHandler().</summary>
  802. public static void UnregisterSpawnHandler(uint assetId)
  803. {
  804. spawnHandlers.Remove(assetId);
  805. unspawnHandlers.Remove(assetId);
  806. }
  807. /// <summary>This clears the registered spawn prefabs and spawn handler functions for this client.</summary>
  808. public static void ClearSpawners()
  809. {
  810. prefabs.Clear();
  811. spawnHandlers.Clear();
  812. unspawnHandlers.Clear();
  813. }
  814. internal static bool InvokeUnSpawnHandler(uint assetId, GameObject obj)
  815. {
  816. if (unspawnHandlers.TryGetValue(assetId, out UnSpawnDelegate handler) && handler != null)
  817. {
  818. handler(obj);
  819. return true;
  820. }
  821. return false;
  822. }
  823. // ready ///////////////////////////////////////////////////////////////
  824. /// <summary>Sends Ready message to server, indicating that we loaded the scene, ready to enter the game.</summary>
  825. // This could be for example when a client enters an ongoing game and
  826. // has finished loading the current scene. The server should respond to
  827. // the SYSTEM_READY event with an appropriate handler which instantiates
  828. // the players object for example.
  829. public static bool Ready()
  830. {
  831. // Debug.Log($"NetworkClient.Ready() called with connection {conn}");
  832. if (ready)
  833. {
  834. Debug.LogError("NetworkClient is already ready. It shouldn't be called twice.");
  835. return false;
  836. }
  837. // need a valid connection to become ready
  838. if (connection == null)
  839. {
  840. Debug.LogError("Ready() called with invalid connection object: conn=null");
  841. return false;
  842. }
  843. // Set these before sending the ReadyMessage, otherwise host client
  844. // will fail in InternalAddPlayer with null readyConnection.
  845. // TODO this is redundant. have one source of truth for .ready
  846. ready = true;
  847. connection.isReady = true;
  848. // Tell server we're ready to have a player object spawned
  849. connection.Send(new ReadyMessage());
  850. return true;
  851. }
  852. // add player //////////////////////////////////////////////////////////
  853. // called from message handler for Owner message
  854. internal static void InternalAddPlayer(NetworkIdentity identity)
  855. {
  856. //Debug.Log("NetworkClient.InternalAddPlayer");
  857. // NOTE: It can be "normal" when changing scenes for the player to be destroyed and recreated.
  858. // But, the player structures are not cleaned up, we'll just replace the old player
  859. localPlayer = identity;
  860. // NOTE: we DONT need to set isClient=true here, because OnStartClient
  861. // is called before OnStartLocalPlayer, hence it's already set.
  862. // localPlayer.isClient = true;
  863. // TODO this check might not be necessary
  864. //if (readyConnection != null)
  865. if (ready && connection != null)
  866. {
  867. connection.identity = identity;
  868. }
  869. else Debug.LogWarning("NetworkClient can't AddPlayer before being ready. Please call NetworkClient.Ready() first. Clients are considered ready after joining the game world.");
  870. }
  871. /// <summary>Sends AddPlayer message to the server, indicating that we want to join the world.</summary>
  872. public static bool AddPlayer()
  873. {
  874. // ensure valid ready connection
  875. if (connection == null)
  876. {
  877. Debug.LogError("AddPlayer requires a valid NetworkClient.connection.");
  878. return false;
  879. }
  880. // UNET checked 'if readyConnection != null'.
  881. // in other words, we need a connection and we need to be ready.
  882. if (!ready)
  883. {
  884. Debug.LogError("AddPlayer requires a ready NetworkClient.");
  885. return false;
  886. }
  887. if (connection.identity != null)
  888. {
  889. Debug.LogError("NetworkClient.AddPlayer: a PlayerController was already added. Did you call AddPlayer twice?");
  890. return false;
  891. }
  892. // Debug.Log($"NetworkClient.AddPlayer() called with connection {readyConnection}");
  893. connection.Send(new AddPlayerMessage());
  894. return true;
  895. }
  896. // spawning ////////////////////////////////////////////////////////////
  897. internal static void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage message)
  898. {
  899. if (message.assetId != 0)
  900. identity.assetId = message.assetId;
  901. if (!identity.gameObject.activeSelf)
  902. {
  903. identity.gameObject.SetActive(true);
  904. }
  905. // apply local values for VR support
  906. identity.transform.localPosition = message.position;
  907. identity.transform.localRotation = message.rotation;
  908. identity.transform.localScale = message.scale;
  909. // configure flags
  910. // the below DeserializeClient call invokes SyncVarHooks.
  911. // flags always need to be initialized before that.
  912. // fixes: https://github.com/MirrorNetworking/Mirror/issues/3259
  913. identity.isOwned = message.isOwner;
  914. identity.netId = message.netId;
  915. if (message.isLocalPlayer)
  916. InternalAddPlayer(identity);
  917. // configure isClient/isLocalPlayer flags.
  918. // => after InternalAddPlayer. can't initialize .isLocalPlayer
  919. // before InternalAddPlayer sets .localPlayer
  920. // => before DeserializeClient, otherwise SyncVar hooks wouldn't
  921. // have isClient/isLocalPlayer set yet.
  922. // fixes: https://github.com/MirrorNetworking/Mirror/issues/3259
  923. InitializeIdentityFlags(identity);
  924. // deserialize components if any payload
  925. // (Count is 0 if there were no components)
  926. if (message.payload.Count > 0)
  927. {
  928. using (NetworkReaderPooled payloadReader = NetworkReaderPool.Get(message.payload))
  929. {
  930. identity.DeserializeClient(payloadReader, true);
  931. }
  932. }
  933. spawned[message.netId] = identity;
  934. if (identity.isOwned) connection?.owned.Add(identity);
  935. // the initial spawn with OnObjectSpawnStarted/Finished calls all
  936. // object's OnStartClient/OnStartLocalPlayer after they were all
  937. // spawned.
  938. // this only happens once though.
  939. // for all future spawns, we need to call OnStartClient/LocalPlayer
  940. // here immediately since there won't be another OnObjectSpawnFinished.
  941. if (isSpawnFinished)
  942. {
  943. InvokeIdentityCallbacks(identity);
  944. }
  945. }
  946. // Finds Existing Object with NetId or spawns a new one using AssetId or sceneId
  947. internal static bool FindOrSpawnObject(SpawnMessage message, out NetworkIdentity identity)
  948. {
  949. // was the object already spawned?
  950. identity = GetExistingObject(message.netId);
  951. // if found, return early
  952. if (identity != null)
  953. {
  954. return true;
  955. }
  956. if (message.assetId == 0 && message.sceneId == 0)
  957. {
  958. Debug.LogError($"OnSpawn message with netId '{message.netId}' has no AssetId or sceneId");
  959. return false;
  960. }
  961. identity = message.sceneId == 0 ? SpawnPrefab(message) : SpawnSceneObject(message.sceneId);
  962. if (identity == null)
  963. {
  964. Debug.LogError($"Could not spawn assetId={message.assetId} scene={message.sceneId:X} netId={message.netId}");
  965. return false;
  966. }
  967. return true;
  968. }
  969. static NetworkIdentity GetExistingObject(uint netid)
  970. {
  971. spawned.TryGetValue(netid, out NetworkIdentity identity);
  972. return identity;
  973. }
  974. static NetworkIdentity SpawnPrefab(SpawnMessage message)
  975. {
  976. // custom spawn handler for this prefab? (for prefab pools etc.)
  977. //
  978. // IMPORTANT: look for spawn handlers BEFORE looking for registered
  979. // prefabs. Unspawning also looks for unspawn handlers
  980. // before falling back to regular Destroy. this needs to
  981. // be consistent.
  982. // https://github.com/vis2k/Mirror/issues/2705
  983. if (spawnHandlers.TryGetValue(message.assetId, out SpawnHandlerDelegate handler))
  984. {
  985. GameObject obj = handler(message);
  986. if (obj == null)
  987. {
  988. Debug.LogError($"Spawn Handler returned null, Handler assetId '{message.assetId}'");
  989. return null;
  990. }
  991. if (!obj.TryGetComponent(out NetworkIdentity identity))
  992. {
  993. Debug.LogError($"Object Spawned by handler did not have a NetworkIdentity, Handler assetId '{message.assetId}'");
  994. return null;
  995. }
  996. return identity;
  997. }
  998. // otherwise look in NetworkManager registered prefabs
  999. if (GetPrefab(message.assetId, out GameObject prefab))
  1000. {
  1001. GameObject obj = GameObject.Instantiate(prefab, message.position, message.rotation);
  1002. //Debug.Log($"Client spawn handler instantiating [netId{message.netId} asset ID:{message.assetId} pos:{message.position} rotation:{message.rotation}]");
  1003. return obj.GetComponent<NetworkIdentity>();
  1004. }
  1005. Debug.LogError($"Failed to spawn server object, did you forget to add it to the NetworkManager? assetId={message.assetId} netId={message.netId}");
  1006. return null;
  1007. }
  1008. static NetworkIdentity SpawnSceneObject(ulong sceneId)
  1009. {
  1010. NetworkIdentity identity = GetAndRemoveSceneObject(sceneId);
  1011. if (identity == null)
  1012. {
  1013. Debug.LogError($"Spawn scene object not found for {sceneId:X}. Make sure that client and server use exactly the same project. This only happens if the hierarchy gets out of sync.");
  1014. // dump the whole spawnable objects dict for easier debugging
  1015. //foreach (KeyValuePair<ulong, NetworkIdentity> kvp in spawnableObjects)
  1016. // Debug.Log($"Spawnable: SceneId={kvp.Key:X} name={kvp.Value.name}");
  1017. }
  1018. //else Debug.Log($"Client spawn for [netId:{msg.netId}] [sceneId:{msg.sceneId:X}] obj:{identity}");
  1019. return identity;
  1020. }
  1021. static NetworkIdentity GetAndRemoveSceneObject(ulong sceneId)
  1022. {
  1023. if (spawnableObjects.TryGetValue(sceneId, out NetworkIdentity identity))
  1024. {
  1025. spawnableObjects.Remove(sceneId);
  1026. return identity;
  1027. }
  1028. return null;
  1029. }
  1030. /// <summary>Call this after loading/unloading a scene in the client after connection to register the spawnable objects</summary>
  1031. public static void PrepareToSpawnSceneObjects()
  1032. {
  1033. // remove existing items, they will be re-added below
  1034. spawnableObjects.Clear();
  1035. // finds all NetworkIdentity currently loaded by unity (includes disabled objects)
  1036. NetworkIdentity[] allIdentities = Resources.FindObjectsOfTypeAll<NetworkIdentity>();
  1037. foreach (NetworkIdentity identity in allIdentities)
  1038. {
  1039. // add all unspawned NetworkIdentities to spawnable objects
  1040. // need to check netId to make sure object is not spawned
  1041. // fixes: https://github.com/MirrorNetworking/Mirror/issues/3541
  1042. // PrepareToSpawnSceneObjects may be called multiple times in case
  1043. // the ObjectSpawnStarted message is received multiple times.
  1044. if (Utils.IsSceneObject(identity) &&
  1045. identity.netId == 0)
  1046. {
  1047. if (spawnableObjects.TryGetValue(identity.sceneId, out NetworkIdentity existingIdentity))
  1048. {
  1049. string msg = $"NetworkClient: Duplicate sceneId {identity.sceneId} detected on {identity.gameObject.name} and {existingIdentity.gameObject.name}\n" +
  1050. $"This can happen if a networked object is persisted in DontDestroyOnLoad through loading / changing to the scene where it originated,\n" +
  1051. $"otherwise you may need to open and re-save the {identity.gameObject.scene} to reset scene id's.";
  1052. Debug.LogWarning(msg, identity.gameObject);
  1053. }
  1054. else
  1055. {
  1056. spawnableObjects.Add(identity.sceneId, identity);
  1057. }
  1058. }
  1059. }
  1060. }
  1061. internal static void OnObjectSpawnStarted(ObjectSpawnStartedMessage _)
  1062. {
  1063. // Debug.Log("SpawnStarted");
  1064. PrepareToSpawnSceneObjects();
  1065. isSpawnFinished = false;
  1066. }
  1067. internal static void OnObjectSpawnFinished(ObjectSpawnFinishedMessage _)
  1068. {
  1069. // paul: Initialize the objects in the same order as they were
  1070. // initialized in the server. This is important if spawned objects
  1071. // use data from scene objects
  1072. foreach (NetworkIdentity identity in spawned.Values.OrderBy(uv => uv.netId))
  1073. {
  1074. // NetworkIdentities should always be removed from .spawned when
  1075. // they are destroyed. for safety, let's double check here.
  1076. if (identity != null)
  1077. {
  1078. BootstrapIdentity(identity);
  1079. }
  1080. else Debug.LogWarning("Found null entry in NetworkClient.spawned. This is unexpected. Was the NetworkIdentity not destroyed properly?");
  1081. }
  1082. isSpawnFinished = true;
  1083. }
  1084. // host mode callbacks /////////////////////////////////////////////////
  1085. static void OnHostClientObjectDestroy(ObjectDestroyMessage message)
  1086. {
  1087. //Debug.Log($"NetworkClient.OnLocalObjectObjDestroy netId:{message.netId}");
  1088. // remove from owned (if any)
  1089. if (spawned.TryGetValue(message.netId, out NetworkIdentity identity))
  1090. connection.owned.Remove(identity);
  1091. spawned.Remove(message.netId);
  1092. }
  1093. static void OnHostClientObjectHide(ObjectHideMessage message)
  1094. {
  1095. //Debug.Log($"ClientScene::OnLocalObjectObjHide netId:{message.netId}");
  1096. if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) &&
  1097. identity != null)
  1098. {
  1099. if (aoi != null)
  1100. aoi.SetHostVisibility(identity, false);
  1101. }
  1102. }
  1103. internal static void OnHostClientSpawn(SpawnMessage message)
  1104. {
  1105. // on host mode, the object already exist in NetworkServer.spawned.
  1106. // simply add it to NetworkClient.spawned too.
  1107. if (NetworkServer.spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null)
  1108. {
  1109. spawned[message.netId] = identity;
  1110. if (message.isOwner) connection.owned.Add(identity);
  1111. // now do the actual 'spawning' on host mode
  1112. if (message.isLocalPlayer)
  1113. InternalAddPlayer(identity);
  1114. // set visibility before invoking OnStartClient etc. callbacks
  1115. if (aoi != null)
  1116. aoi.SetHostVisibility(identity, true);
  1117. identity.isOwned = message.isOwner;
  1118. BootstrapIdentity(identity);
  1119. }
  1120. }
  1121. // client-only mode callbacks //////////////////////////////////////////
  1122. static void OnEntityStateMessage(EntityStateMessage message)
  1123. {
  1124. // Debug.Log($"NetworkClient.OnUpdateVarsMessage {msg.netId}");
  1125. if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null)
  1126. {
  1127. using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload))
  1128. identity.DeserializeClient(reader, false);
  1129. }
  1130. else Debug.LogWarning($"Did not find target for sync message for {message.netId}. Were all prefabs added to the NetworkManager's spawnable list?\nNote: this can be completely normal because UDP messages may arrive out of order, so this message might have arrived after a Destroy message.");
  1131. }
  1132. static void OnRPCMessage(RpcMessage message)
  1133. {
  1134. // Debug.Log($"NetworkClient.OnRPCMessage hash:{message.functionHash} netId:{message.netId}");
  1135. if (spawned.TryGetValue(message.netId, out NetworkIdentity identity))
  1136. {
  1137. using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload))
  1138. identity.HandleRemoteCall(message.componentIndex, message.functionHash, RemoteCallType.ClientRpc, reader);
  1139. }
  1140. // Rpcs often can't be applied if interest management unspawned them
  1141. }
  1142. static void OnObjectHide(ObjectHideMessage message) => DestroyObject(message.netId);
  1143. internal static void OnObjectDestroy(ObjectDestroyMessage message) => DestroyObject(message.netId);
  1144. internal static void OnSpawn(SpawnMessage message)
  1145. {
  1146. // Debug.Log($"Client spawn handler instantiating netId={msg.netId} assetID={msg.assetId} sceneId={msg.sceneId:X} pos={msg.position}");
  1147. if (FindOrSpawnObject(message, out NetworkIdentity identity))
  1148. {
  1149. ApplySpawnPayload(identity, message);
  1150. }
  1151. }
  1152. internal static void OnChangeOwner(ChangeOwnerMessage message)
  1153. {
  1154. NetworkIdentity identity = GetExistingObject(message.netId);
  1155. if (identity != null)
  1156. ChangeOwner(identity, message);
  1157. else
  1158. Debug.LogError($"OnChangeOwner: Could not find object with netId {message.netId}");
  1159. }
  1160. // ChangeOwnerMessage contains new 'owned' and new 'localPlayer'
  1161. // that we need to apply to the identity.
  1162. internal static void ChangeOwner(NetworkIdentity identity, ChangeOwnerMessage message)
  1163. {
  1164. // local player before, but not anymore?
  1165. // call OnStopLocalPlayer before setting new values.
  1166. if (identity.isLocalPlayer && !message.isLocalPlayer)
  1167. {
  1168. identity.OnStopLocalPlayer();
  1169. }
  1170. // set ownership flag (aka authority)
  1171. identity.isOwned = message.isOwner;
  1172. // Add / Remove to client's connectionToServer.owned hashset.
  1173. if (identity.isOwned)
  1174. connection?.owned.Add(identity);
  1175. else
  1176. connection?.owned.Remove(identity);
  1177. // Call OnStartAuthority / OnStopAuthority
  1178. identity.NotifyAuthority();
  1179. // set localPlayer flag
  1180. identity.isLocalPlayer = message.isLocalPlayer;
  1181. // identity is now local player. set our static helper field to it.
  1182. if (identity.isLocalPlayer)
  1183. {
  1184. localPlayer = identity;
  1185. identity.connectionToServer = connection;
  1186. identity.OnStartLocalPlayer();
  1187. }
  1188. // identity's isLocalPlayer was set to false.
  1189. // clear our static localPlayer IF (and only IF) it was that one before.
  1190. else if (localPlayer == identity)
  1191. {
  1192. localPlayer = null;
  1193. // TODO set .connectionToServer to null for old local player?
  1194. // since we set it in the above 'if' case too.
  1195. }
  1196. }
  1197. // set up NetworkIdentity flags on the client.
  1198. // needs to be separate from invoking callbacks.
  1199. // cleaner, and some places need to set flags first.
  1200. static void InitializeIdentityFlags(NetworkIdentity identity)
  1201. {
  1202. // initialize flags before invoking callbacks.
  1203. // this way isClient/isLocalPlayer is correct during callbacks.
  1204. // fixes: https://github.com/MirrorNetworking/Mirror/issues/3362
  1205. identity.isClient = true;
  1206. identity.isLocalPlayer = localPlayer == identity;
  1207. // .connectionToServer is only available for local players.
  1208. // set it here, before invoking any callbacks.
  1209. // this way it's available in _all_ callbacks.
  1210. if (identity.isLocalPlayer)
  1211. identity.connectionToServer = connection;
  1212. }
  1213. // invoke NetworkIdentity callbacks on the client.
  1214. // needs to be separate from configuring flags.
  1215. // cleaner, and some places need to set flags first.
  1216. static void InvokeIdentityCallbacks(NetworkIdentity identity)
  1217. {
  1218. // invoke OnStartAuthority
  1219. identity.NotifyAuthority();
  1220. // invoke OnStartClient
  1221. identity.OnStartClient();
  1222. // invoke OnStartLocalPlayer
  1223. if (identity.isLocalPlayer)
  1224. identity.OnStartLocalPlayer();
  1225. }
  1226. // configure flags & invoke callbacks
  1227. static void BootstrapIdentity(NetworkIdentity identity)
  1228. {
  1229. InitializeIdentityFlags(identity);
  1230. InvokeIdentityCallbacks(identity);
  1231. }
  1232. // broadcast ///////////////////////////////////////////////////////////
  1233. static void BroadcastTimeSnapshot()
  1234. {
  1235. Send(new TimeSnapshotMessage(), Channels.Unreliable);
  1236. }
  1237. // make sure Broadcast() is only called every sendInterval.
  1238. // calling it every update() would require too much bandwidth.
  1239. static void Broadcast()
  1240. {
  1241. // joined the world yet?
  1242. if (!connection.isReady) return;
  1243. // nothing to do in host mode. server already knows the state.
  1244. if (NetworkServer.active) return;
  1245. // send time snapshot every sendInterval.
  1246. BroadcastTimeSnapshot();
  1247. // for each entity that the client owns
  1248. foreach (NetworkIdentity identity in connection.owned)
  1249. {
  1250. // make sure it's not null or destroyed.
  1251. // (which can happen if someone uses
  1252. // GameObject.Destroy instead of
  1253. // NetworkServer.Destroy)
  1254. if (identity != null)
  1255. {
  1256. using (NetworkWriterPooled writer = NetworkWriterPool.Get())
  1257. {
  1258. // get serialization for this entity viewed by this connection
  1259. // (if anything was serialized this time)
  1260. identity.SerializeClient(writer);
  1261. if (writer.Position > 0)
  1262. {
  1263. // send state update message
  1264. EntityStateMessage message = new EntityStateMessage
  1265. {
  1266. netId = identity.netId,
  1267. payload = writer.ToArraySegment()
  1268. };
  1269. Send(message);
  1270. }
  1271. }
  1272. }
  1273. // spawned list should have no null entries because we
  1274. // always call Remove in OnObjectDestroy everywhere.
  1275. // if it does have null then we missed something.
  1276. else Debug.LogWarning($"Found 'null' entry in owned list for client. This is unexpected behaviour.");
  1277. }
  1278. }
  1279. // update //////////////////////////////////////////////////////////////
  1280. // NetworkEarlyUpdate called before any Update/FixedUpdate
  1281. // (we add this to the UnityEngine in NetworkLoop)
  1282. internal static void NetworkEarlyUpdate()
  1283. {
  1284. // process all incoming messages first before updating the world
  1285. if (Transport.active != null)
  1286. Transport.active.ClientEarlyUpdate();
  1287. // time snapshot interpolation
  1288. UpdateTimeInterpolation();
  1289. }
  1290. // NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate
  1291. // (we add this to the UnityEngine in NetworkLoop)
  1292. internal static void NetworkLateUpdate()
  1293. {
  1294. // broadcast ClientToServer components while active
  1295. if (active)
  1296. {
  1297. // broadcast every sendInterval.
  1298. // AccurateInterval to avoid update frequency inaccuracy issues:
  1299. // https://github.com/vis2k/Mirror/pull/3153
  1300. //
  1301. // for example, host mode server doesn't set .targetFrameRate.
  1302. // Broadcast() would be called every tick.
  1303. // snapshots might be sent way too often, etc.
  1304. //
  1305. // during tests, we always call Broadcast() though.
  1306. //
  1307. // also important for syncInterval=0 components like
  1308. // NetworkTransform, so they can sync on same interval as time
  1309. // snapshots _but_ not every single tick.
  1310. //
  1311. // Unity 2019 doesn't have Time.timeAsDouble yet
  1312. if (!Application.isPlaying ||
  1313. AccurateInterval.Elapsed(NetworkTime.localTime, sendInterval, ref lastSendTime))
  1314. {
  1315. Broadcast();
  1316. }
  1317. UpdateConnectionQuality();
  1318. }
  1319. // Connection Quality //////////////////////////////////////////////////
  1320. // uses 'pragmatic' version based on snapshot interpolation by default.
  1321. void UpdateConnectionQuality()
  1322. {
  1323. // only recalculate every few seconds
  1324. // we don't want to fire Good->Bad->Good->Bad dozens of times per second.
  1325. if (connectionQualityInterval > 0 && NetworkTime.time > lastConnectionQualityUpdate + connectionQualityInterval)
  1326. {
  1327. lastConnectionQualityUpdate = NetworkTime.time;
  1328. switch (connectionQualityMethod)
  1329. {
  1330. case ConnectionQualityMethod.Simple:
  1331. connectionQuality = ConnectionQualityHeuristics.Simple(NetworkTime.rtt, NetworkTime.rttVariance);
  1332. break;
  1333. case ConnectionQualityMethod.Pragmatic:
  1334. connectionQuality = ConnectionQualityHeuristics.Pragmatic(initialBufferTime, bufferTime);
  1335. break;
  1336. }
  1337. if (lastConnectionQuality != connectionQuality)
  1338. {
  1339. // Invoke the event before assigning the new value so
  1340. // the event handler can compare old and new values.
  1341. onConnectionQualityChanged?.Invoke(lastConnectionQuality, connectionQuality);
  1342. lastConnectionQuality = connectionQuality;
  1343. }
  1344. }
  1345. }
  1346. // update connections to flush out messages _after_ broadcast
  1347. // local connection?
  1348. if (connection is LocalConnectionToServer localConnection)
  1349. {
  1350. localConnection.Update();
  1351. }
  1352. // remote connection?
  1353. else if (connection is NetworkConnectionToServer remoteConnection)
  1354. {
  1355. // only update things while connected
  1356. if (active && connectState == ConnectState.Connected)
  1357. {
  1358. // update NetworkTime
  1359. NetworkTime.UpdateClient();
  1360. // update connection to flush out batched messages
  1361. remoteConnection.Update();
  1362. }
  1363. }
  1364. // process all outgoing messages after updating the world
  1365. if (Transport.active != null)
  1366. Transport.active.ClientLateUpdate();
  1367. }
  1368. // destroy /////////////////////////////////////////////////////////////
  1369. /// <summary>Destroys all networked objects on the client.</summary>
  1370. // Note: NetworkServer.CleanupNetworkIdentities does the same on server.
  1371. public static void DestroyAllClientObjects()
  1372. {
  1373. // user can modify spawned lists which causes InvalidOperationException
  1374. // list can modified either in UnSpawnHandler or in OnDisable/OnDestroy
  1375. // we need the Try/Catch so that the rest of the shutdown does not get stopped
  1376. try
  1377. {
  1378. foreach (NetworkIdentity identity in spawned.Values)
  1379. {
  1380. if (identity != null && identity.gameObject != null)
  1381. {
  1382. if (identity.isLocalPlayer)
  1383. identity.OnStopLocalPlayer();
  1384. identity.OnStopClient();
  1385. // NetworkClient.Shutdown calls DestroyAllClientObjects.
  1386. // which destroys all objects in NetworkClient.spawned.
  1387. // => NC.spawned contains owned & observed objects
  1388. // => in host mode, we CAN NOT destroy observed objects.
  1389. // => that would destroy them other connection's objects
  1390. // on the host server, making them disconnect.
  1391. // https://github.com/vis2k/Mirror/issues/2954
  1392. bool hostOwned = identity.connectionToServer is LocalConnectionToServer;
  1393. bool shouldDestroy = !identity.isServer || hostOwned;
  1394. if (shouldDestroy)
  1395. {
  1396. bool wasUnspawned = InvokeUnSpawnHandler(identity.assetId, identity.gameObject);
  1397. // unspawned objects should be reset for reuse later.
  1398. if (wasUnspawned)
  1399. {
  1400. identity.Reset();
  1401. }
  1402. // without unspawn handler, we need to disable/destroy.
  1403. else
  1404. {
  1405. // scene objects are reset and disabled.
  1406. // they always stay in the scene, we don't destroy them.
  1407. if (identity.sceneId != 0)
  1408. {
  1409. identity.Reset();
  1410. identity.gameObject.SetActive(false);
  1411. }
  1412. // spawned objects are destroyed
  1413. else
  1414. {
  1415. GameObject.Destroy(identity.gameObject);
  1416. }
  1417. }
  1418. }
  1419. }
  1420. }
  1421. spawned.Clear();
  1422. connection?.owned.Clear();
  1423. }
  1424. catch (InvalidOperationException e)
  1425. {
  1426. Debug.LogException(e);
  1427. Debug.LogError("Could not DestroyAllClientObjects because spawned list was modified during loop, make sure you are not modifying NetworkIdentity.spawned by calling NetworkServer.Destroy or NetworkServer.Spawn in OnDestroy or OnDisable.");
  1428. }
  1429. }
  1430. static void DestroyObject(uint netId)
  1431. {
  1432. // Debug.Log($"NetworkClient.OnObjDestroy netId: {netId}");
  1433. if (spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null)
  1434. {
  1435. if (identity.isLocalPlayer)
  1436. identity.OnStopLocalPlayer();
  1437. identity.OnStopClient();
  1438. // custom unspawn handler for this prefab? (for prefab pools etc.)
  1439. if (InvokeUnSpawnHandler(identity.assetId, identity.gameObject))
  1440. {
  1441. // reset object after user's handler
  1442. identity.Reset();
  1443. }
  1444. // otherwise fall back to default Destroy
  1445. else if (identity.sceneId == 0)
  1446. {
  1447. // don't call reset before destroy so that values are still set in OnDestroy
  1448. GameObject.Destroy(identity.gameObject);
  1449. }
  1450. // scene object.. disable it in scene instead of destroying
  1451. else
  1452. {
  1453. identity.gameObject.SetActive(false);
  1454. spawnableObjects[identity.sceneId] = identity;
  1455. // reset for scene objects
  1456. identity.Reset();
  1457. }
  1458. // remove from dictionary no matter how it is unspawned
  1459. connection.owned.Remove(identity); // if any
  1460. spawned.Remove(netId);
  1461. }
  1462. //else Debug.LogWarning($"Did not find target for destroy message for {netId}");
  1463. }
  1464. // shutdown ////////////////////////////////////////////////////////////
  1465. /// <summary>Shutdown the client.</summary>
  1466. // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload
  1467. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
  1468. public static void Shutdown()
  1469. {
  1470. //Debug.Log("Shutting down client.");
  1471. // objects need to be destroyed before spawners are cleared
  1472. // fixes: https://github.com/MirrorNetworking/Mirror/issues/3334
  1473. DestroyAllClientObjects();
  1474. // calls prefabs.Clear();
  1475. // calls spawnHandlers.Clear();
  1476. // calls unspawnHandlers.Clear();
  1477. ClearSpawners();
  1478. spawned.Clear();
  1479. connection?.owned.Clear();
  1480. handlers.Clear();
  1481. spawnableObjects.Clear();
  1482. // IMPORTANT: do NOT call NetworkIdentity.ResetStatics() here!
  1483. // calling StopClient() in host mode would reset nextNetId to 1,
  1484. // causing next connection to have a duplicate netId accidentally.
  1485. // => see also: https://github.com/vis2k/Mirror/issues/2954
  1486. //NetworkIdentity.ResetStatics();
  1487. // => instead, reset only the client sided statics.
  1488. NetworkIdentity.ResetClientStatics();
  1489. // disconnect the client connection.
  1490. // we do NOT call Transport.Shutdown, because someone only called
  1491. // NetworkClient.Shutdown. we can't assume that the server is
  1492. // supposed to be shut down too!
  1493. if (Transport.active != null)
  1494. Transport.active.ClientDisconnect();
  1495. // reset statics
  1496. connectState = ConnectState.None;
  1497. connection = null;
  1498. localPlayer = null;
  1499. ready = false;
  1500. isSpawnFinished = false;
  1501. isLoadingScene = false;
  1502. lastSendTime = 0;
  1503. unbatcher = new Unbatcher();
  1504. // clear events. someone might have hooked into them before, but
  1505. // we don't want to use those hooks after Shutdown anymore.
  1506. OnConnectedEvent = null;
  1507. OnDisconnectedEvent = null;
  1508. OnErrorEvent = null;
  1509. }
  1510. // GUI /////////////////////////////////////////////////////////////////
  1511. // called from NetworkManager to display timeline interpolation status.
  1512. // useful to indicate catchup / slowdown / dynamic adjustment etc.
  1513. public static void OnGUI()
  1514. {
  1515. // only if in world
  1516. if (!ready) return;
  1517. GUILayout.BeginArea(new Rect(10, 5, 1020, 50));
  1518. GUILayout.BeginHorizontal("Box");
  1519. GUILayout.Label("Snapshot Interp.:");
  1520. // color while catching up / slowing down
  1521. if (localTimescale > 1) GUI.color = Color.green; // green traffic light = go fast
  1522. else if (localTimescale < 1) GUI.color = Color.red; // red traffic light = go slow
  1523. else GUI.color = Color.white;
  1524. GUILayout.Box($"timeline: {localTimeline:F2}");
  1525. GUILayout.Box($"buffer: {snapshots.Count}");
  1526. GUILayout.Box($"DriftEMA: {NetworkClient.driftEma.Value:F2}");
  1527. GUILayout.Box($"DelTimeEMA: {NetworkClient.deliveryTimeEma.Value:F2}");
  1528. GUILayout.Box($"timescale: {localTimescale:F2}");
  1529. GUILayout.Box($"BTM: {NetworkClient.bufferTimeMultiplier:F2}"); // current dynamically adjusted multiplier
  1530. GUILayout.Box($"RTT: {NetworkTime.rtt * 1000:F0}ms");
  1531. GUILayout.Box($"PredErrUNADJ: {NetworkTime.predictionErrorUnadjusted * 1000:F0}ms");
  1532. GUILayout.Box($"PredErrADJ: {NetworkTime.predictionErrorAdjusted * 1000:F0}ms");
  1533. GUILayout.EndHorizontal();
  1534. GUILayout.EndArea();
  1535. }
  1536. }
  1537. }