NetworkClient.cs 75 KB

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