NetworkManager.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using kcp2k;
  6. using UnityEngine;
  7. using UnityEngine.SceneManagement;
  8. using UnityEngine.Serialization;
  9. namespace Mirror
  10. {
  11. public enum PlayerSpawnMethod { Random, RoundRobin }
  12. public enum NetworkManagerMode { Offline, ServerOnly, ClientOnly, Host }
  13. [DisallowMultipleComponent]
  14. [AddComponentMenu("Network/NetworkManager")]
  15. [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-manager")]
  16. public class NetworkManager : MonoBehaviour
  17. {
  18. /// <summary>Enable to keep NetworkManager alive when changing scenes.</summary>
  19. // This should be set if your game has a single NetworkManager that exists for the lifetime of the process. If there is a NetworkManager in each scene, then this should not be set.</para>
  20. [Header("Configuration")]
  21. [FormerlySerializedAs("m_DontDestroyOnLoad")]
  22. [Tooltip("Should the Network Manager object be persisted through scene changes?")]
  23. public bool dontDestroyOnLoad = true;
  24. // Deprecated 2021-03-10
  25. // Temporary bool to allow Network Manager to persist to offline scene
  26. // Based on Discord convo, BigBox is invoking StopHost in startup sequence, bouncing the server and clients back to offline scene, which resets Network Manager.
  27. // Request is for a checkbox to persist Network Manager to offline scene, despite the collision and warning.
  28. [Obsolete("This was added temporarily and will be removed in a future release.")]
  29. [Tooltip("Should the Network Manager object be persisted through scene change to the offline scene?")]
  30. public bool PersistNetworkManagerToOfflineScene;
  31. /// <summary>Multiplayer games should always run in the background so the network doesn't time out.</summary>
  32. [FormerlySerializedAs("m_RunInBackground")]
  33. [Tooltip("Multiplayer games should always run in the background so the network doesn't time out.")]
  34. public bool runInBackground = true;
  35. /// <summary>Should the server auto-start when 'Server Build' is checked in build settings</summary>
  36. [Tooltip("Should the server auto-start when 'Server Build' is checked in build settings")]
  37. [FormerlySerializedAs("startOnHeadless")]
  38. public bool autoStartServerBuild = true;
  39. /// <summary>Server Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE.</summary>
  40. [Tooltip("Server Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE.")]
  41. public int serverTickRate = 30;
  42. /// <summary>Automatically switch to this scene upon going offline (on start / on disconnect / on shutdown).</summary>
  43. [Header("Scene Management")]
  44. [Scene]
  45. [FormerlySerializedAs("m_OfflineScene")]
  46. [Tooltip("Scene that Mirror will switch to when the client or server is stopped")]
  47. public string offlineScene = "";
  48. /// <summary>Automatically switch to this scene upon going online (after connect/startserver).</summary>
  49. [Scene]
  50. [FormerlySerializedAs("m_OnlineScene")]
  51. [Tooltip("Scene that Mirror will switch to when the server is started. Clients will recieve a Scene Message to load the server's current scene when they connect.")]
  52. public string onlineScene = "";
  53. // transport layer
  54. [Header("Network Info")]
  55. [Tooltip("Transport component attached to this object that server and client will use to connect")]
  56. [SerializeField]
  57. protected Transport transport;
  58. /// <summary>Server's address for clients to connect to.</summary>
  59. [FormerlySerializedAs("m_NetworkAddress")]
  60. [Tooltip("Network Address where the client should connect to the server. Server does not use this for anything.")]
  61. public string networkAddress = "localhost";
  62. /// <summary>The maximum number of concurrent network connections to support.</summary>
  63. [FormerlySerializedAs("m_MaxConnections")]
  64. [Tooltip("Maximum number of concurrent connections.")]
  65. public int maxConnections = 100;
  66. // Deprecated 2021-05-10
  67. [Obsolete("Transport is responsible for timeouts.")]
  68. public bool disconnectInactiveConnections;
  69. // Deprecated 2021-05-10
  70. [Obsolete("Transport is responsible for timeouts. Configure the Transport's timeout setting instead.")]
  71. public float disconnectInactiveTimeout = 60f;
  72. [Header("Authentication")]
  73. [Tooltip("Authentication component attached to this object")]
  74. public NetworkAuthenticator authenticator;
  75. /// <summary>The default prefab to be used to create player objects on the server.</summary>
  76. // Player objects are created in the default handler for AddPlayer() on
  77. // the server. Implementing OnServerAddPlayer overrides this behaviour.
  78. [Header("Player Object")]
  79. [FormerlySerializedAs("m_PlayerPrefab")]
  80. [Tooltip("Prefab of the player object. Prefab must have a Network Identity component. May be an empty game object or a full avatar.")]
  81. public GameObject playerPrefab;
  82. /// <summary>Enable to automatically create player objects on connect and on scene change.</summary>
  83. [FormerlySerializedAs("m_AutoCreatePlayer")]
  84. [Tooltip("Should Mirror automatically spawn the player after scene change?")]
  85. public bool autoCreatePlayer = true;
  86. /// <summary>Where to spawn players.</summary>
  87. [FormerlySerializedAs("m_PlayerSpawnMethod")]
  88. [Tooltip("Round Robin or Random order of Start Position selection")]
  89. public PlayerSpawnMethod playerSpawnMethod;
  90. /// <summary>Prefabs that can be spawned over the network need to be registered here.</summary>
  91. [FormerlySerializedAs("m_SpawnPrefabs"), HideInInspector]
  92. public List<GameObject> spawnPrefabs = new List<GameObject>();
  93. /// <summary>List of transforms populated by NetworkStartPositions</summary>
  94. public static List<Transform> startPositions = new List<Transform>();
  95. public static int startPositionIndex;
  96. /// <summary>The one and only NetworkManager</summary>
  97. public static NetworkManager singleton { get; private set; }
  98. /// <summary>Number of active player objects across all connections on the server.</summary>
  99. public int numPlayers => NetworkServer.connections.Count(kv => kv.Value.identity != null);
  100. /// <summary>True if the server is running or client is connected/connecting.</summary>
  101. public bool isNetworkActive => NetworkServer.active || NetworkClient.active;
  102. // TODO remove this
  103. static NetworkConnection clientReadyConnection;
  104. /// <summary>True if the client loaded a new scene when connecting to the server.</summary>
  105. // This is set before OnClientConnect is called, so it can be checked
  106. // there to perform different logic if a scene load occurred.
  107. [NonSerialized]
  108. public bool clientLoadedScene;
  109. // helper enum to know if we started the networkmanager as server/client/host.
  110. // -> this is necessary because when StartHost changes server scene to
  111. // online scene, FinishLoadScene is called and the host client isn't
  112. // connected yet (no need to connect it before server was fully set up).
  113. // in other words, we need this to know which mode we are running in
  114. // during FinishLoadScene.
  115. public NetworkManagerMode mode { get; private set; }
  116. // virtual so that inheriting classes' OnValidate() can call base.OnValidate() too
  117. public virtual void OnValidate()
  118. {
  119. // add transport if there is none yet. makes upgrading easier.
  120. if (transport == null)
  121. {
  122. // was a transport added yet? if not, add one
  123. transport = GetComponent<Transport>();
  124. if (transport == null)
  125. {
  126. transport = gameObject.AddComponent<KcpTransport>();
  127. Debug.Log("NetworkManager: added default Transport because there was none yet.");
  128. }
  129. #if UNITY_EDITOR
  130. // For some insane reason, this line fails when building unless wrapped in this define. Stupid but true.
  131. // error CS0234: The type or namespace name 'Undo' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
  132. UnityEditor.Undo.RecordObject(gameObject, "Added default Transport");
  133. #endif
  134. }
  135. // always >= 0
  136. maxConnections = Mathf.Max(maxConnections, 0);
  137. if (playerPrefab != null && playerPrefab.GetComponent<NetworkIdentity>() == null)
  138. {
  139. Debug.LogError("NetworkManager - Player Prefab must have a NetworkIdentity.");
  140. playerPrefab = null;
  141. }
  142. // This avoids the mysterious "Replacing existing prefab with assetId ... Old prefab 'Player', New prefab 'Player'" warning.
  143. if (playerPrefab != null && spawnPrefabs.Contains(playerPrefab))
  144. {
  145. Debug.LogWarning("NetworkManager - Player Prefab should not be added to Registered Spawnable Prefabs list...removed it.");
  146. spawnPrefabs.Remove(playerPrefab);
  147. }
  148. }
  149. // virtual so that inheriting classes' Awake() can call base.Awake() too
  150. public virtual void Awake()
  151. {
  152. // Don't allow collision-destroyed second instance to continue.
  153. if (!InitializeSingleton()) return;
  154. Debug.Log("Mirror | mirror-networking.com | discord.gg/N9QVxbM");
  155. // Set the networkSceneName to prevent a scene reload
  156. // if client connection to server fails.
  157. networkSceneName = offlineScene;
  158. // setup OnSceneLoaded callback
  159. SceneManager.sceneLoaded += OnSceneLoaded;
  160. }
  161. // virtual so that inheriting classes' Start() can call base.Start() too
  162. public virtual void Start()
  163. {
  164. // headless mode? then start the server
  165. // can't do this in Awake because Awake is for initialization.
  166. // some transports might not be ready until Start.
  167. //
  168. // (tick rate is applied in StartServer!)
  169. #if UNITY_SERVER
  170. if (autoStartServerBuild)
  171. {
  172. StartServer();
  173. }
  174. #endif
  175. }
  176. // virtual so that inheriting classes' LateUpdate() can call base.LateUpdate() too
  177. public virtual void LateUpdate()
  178. {
  179. UpdateScene();
  180. }
  181. // keep the online scene change check in a separate function
  182. bool IsServerOnlineSceneChangeNeeded()
  183. {
  184. // Only change scene if the requested online scene is not blank, and is not already loaded
  185. return !string.IsNullOrEmpty(onlineScene) && !IsSceneActive(onlineScene) && onlineScene != offlineScene;
  186. }
  187. public static bool IsSceneActive(string scene)
  188. {
  189. Scene activeScene = SceneManager.GetActiveScene();
  190. return activeScene.path == scene || activeScene.name == scene;
  191. }
  192. // full server setup code, without spawning objects yet
  193. void SetupServer()
  194. {
  195. // Debug.Log("NetworkManager SetupServer");
  196. InitializeSingleton();
  197. if (runInBackground)
  198. Application.runInBackground = true;
  199. if (authenticator != null)
  200. {
  201. authenticator.OnStartServer();
  202. authenticator.OnServerAuthenticated.AddListener(OnServerAuthenticated);
  203. }
  204. ConfigureHeadlessFrameRate();
  205. // Copy auto-disconnect settings to NetworkServer
  206. #pragma warning disable 618
  207. NetworkServer.disconnectInactiveTimeout = disconnectInactiveTimeout;
  208. NetworkServer.disconnectInactiveConnections = disconnectInactiveConnections;
  209. #pragma warning restore 618
  210. // start listening to network connections
  211. NetworkServer.Listen(maxConnections);
  212. // call OnStartServer AFTER Listen, so that NetworkServer.active is
  213. // true and we can call NetworkServer.Spawn in OnStartServer
  214. // overrides.
  215. // (useful for loading & spawning stuff from database etc.)
  216. //
  217. // note: there is no risk of someone connecting after Listen() and
  218. // before OnStartServer() because this all runs in one thread
  219. // and we don't start processing connects until Update.
  220. OnStartServer();
  221. // this must be after Listen(), since that registers the default message handlers
  222. RegisterServerMessages();
  223. }
  224. /// <summary>Starts the server, listening for incoming connections.</summary>
  225. public void StartServer()
  226. {
  227. if (NetworkServer.active)
  228. {
  229. Debug.LogWarning("Server already started.");
  230. return;
  231. }
  232. mode = NetworkManagerMode.ServerOnly;
  233. // StartServer is inherently ASYNCHRONOUS (=doesn't finish immediately)
  234. //
  235. // Here is what it does:
  236. // Listen
  237. // if onlineScene:
  238. // LoadSceneAsync
  239. // ...
  240. // FinishLoadSceneServerOnly
  241. // SpawnObjects
  242. // else:
  243. // SpawnObjects
  244. //
  245. // there is NO WAY to make it synchronous because both LoadSceneAsync
  246. // and LoadScene do not finish loading immediately. as long as we
  247. // have the onlineScene feature, it will be asynchronous!
  248. SetupServer();
  249. // scene change needed? then change scene and spawn afterwards.
  250. if (IsServerOnlineSceneChangeNeeded())
  251. {
  252. ServerChangeScene(onlineScene);
  253. }
  254. // otherwise spawn directly
  255. else
  256. {
  257. NetworkServer.SpawnObjects();
  258. }
  259. }
  260. /// <summary>Starts the client, connects it to the server with networkAddress.</summary>
  261. public void StartClient()
  262. {
  263. if (NetworkClient.active)
  264. {
  265. Debug.LogWarning("Client already started.");
  266. return;
  267. }
  268. mode = NetworkManagerMode.ClientOnly;
  269. InitializeSingleton();
  270. if (runInBackground)
  271. Application.runInBackground = true;
  272. if (authenticator != null)
  273. {
  274. authenticator.OnStartClient();
  275. authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated);
  276. }
  277. // In case this is a headless client...
  278. ConfigureHeadlessFrameRate();
  279. RegisterClientMessages();
  280. if (string.IsNullOrEmpty(networkAddress))
  281. {
  282. Debug.LogError("Must set the Network Address field in the manager");
  283. return;
  284. }
  285. // Debug.Log("NetworkManager StartClient address:" + networkAddress);
  286. NetworkClient.Connect(networkAddress);
  287. OnStartClient();
  288. }
  289. /// <summary>Starts the client, connects it to the server via Uri</summary>
  290. public void StartClient(Uri uri)
  291. {
  292. if (NetworkClient.active)
  293. {
  294. Debug.LogWarning("Client already started.");
  295. return;
  296. }
  297. mode = NetworkManagerMode.ClientOnly;
  298. InitializeSingleton();
  299. if (runInBackground)
  300. Application.runInBackground = true;
  301. if (authenticator != null)
  302. {
  303. authenticator.OnStartClient();
  304. authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated);
  305. }
  306. RegisterClientMessages();
  307. // Debug.Log("NetworkManager StartClient address:" + uri);
  308. networkAddress = uri.Host;
  309. NetworkClient.Connect(uri);
  310. OnStartClient();
  311. }
  312. /// <summary>Starts a network "host" - a server and client in the same application.</summary>
  313. public void StartHost()
  314. {
  315. if (NetworkServer.active || NetworkClient.active)
  316. {
  317. Debug.LogWarning("Server or Client already started.");
  318. return;
  319. }
  320. mode = NetworkManagerMode.Host;
  321. // StartHost is inherently ASYNCHRONOUS (=doesn't finish immediately)
  322. //
  323. // Here is what it does:
  324. // Listen
  325. // ConnectHost
  326. // if onlineScene:
  327. // LoadSceneAsync
  328. // ...
  329. // FinishLoadSceneHost
  330. // FinishStartHost
  331. // SpawnObjects
  332. // StartHostClient <= not guaranteed to happen after SpawnObjects if onlineScene is set!
  333. // ClientAuth
  334. // success: server sends changescene msg to client
  335. // else:
  336. // FinishStartHost
  337. //
  338. // there is NO WAY to make it synchronous because both LoadSceneAsync
  339. // and LoadScene do not finish loading immediately. as long as we
  340. // have the onlineScene feature, it will be asynchronous!
  341. // setup server first
  342. SetupServer();
  343. // call OnStartHost AFTER SetupServer. this way we can use
  344. // NetworkServer.Spawn etc. in there too. just like OnStartServer
  345. // is called after the server is actually properly started.
  346. OnStartHost();
  347. // scene change needed? then change scene and spawn afterwards.
  348. // => BEFORE host client connects. if client auth succeeds then the
  349. // server tells it to load 'onlineScene'. we can't do that if
  350. // server is still in 'offlineScene'. so load on server first.
  351. if (IsServerOnlineSceneChangeNeeded())
  352. {
  353. // call FinishStartHost after changing scene.
  354. finishStartHostPending = true;
  355. ServerChangeScene(onlineScene);
  356. }
  357. // otherwise call FinishStartHost directly
  358. else
  359. {
  360. FinishStartHost();
  361. }
  362. }
  363. // This may be set true in StartHost and is evaluated in FinishStartHost
  364. bool finishStartHostPending;
  365. // FinishStartHost is guaranteed to be called after the host server was
  366. // fully started and all the asynchronous StartHost magic is finished
  367. // (= scene loading), or immediately if there was no asynchronous magic.
  368. //
  369. // note: we don't really need FinishStartClient/FinishStartServer. the
  370. // host version is enough.
  371. void FinishStartHost()
  372. {
  373. // ConnectHost needs to be called BEFORE SpawnObjects:
  374. // https://github.com/vis2k/Mirror/pull/1249/
  375. // -> this sets NetworkServer.localConnection.
  376. // -> localConnection needs to be set before SpawnObjects because:
  377. // -> SpawnObjects calls OnStartServer in all NetworkBehaviours
  378. // -> OnStartServer might spawn an object and set [SyncVar(hook="OnColorChanged")] object.color = green;
  379. // -> this calls SyncVar.set (generated by Weaver), which has
  380. // a custom case for host mode (because host mode doesn't
  381. // get OnDeserialize calls, where SyncVar hooks are usually
  382. // called):
  383. //
  384. // if (!SyncVarEqual(value, ref color))
  385. // {
  386. // if (NetworkServer.localClientActive && !getSyncVarHookGuard(1uL))
  387. // {
  388. // setSyncVarHookGuard(1uL, value: true);
  389. // OnColorChangedHook(value);
  390. // setSyncVarHookGuard(1uL, value: false);
  391. // }
  392. // SetSyncVar(value, ref color, 1uL);
  393. // }
  394. //
  395. // -> localClientActive needs to be true, otherwise the hook
  396. // isn't called in host mode!
  397. //
  398. // TODO call this after spawnobjects and worry about the syncvar hook fix later?
  399. NetworkClient.ConnectHost();
  400. // server scene was loaded. now spawn all the objects
  401. NetworkServer.SpawnObjects();
  402. // connect client and call OnStartClient AFTER server scene was
  403. // loaded and all objects were spawned.
  404. // DO NOT do this earlier. it would cause race conditions where a
  405. // client will do things before the server is even fully started.
  406. //Debug.Log("StartHostClient called");
  407. StartHostClient();
  408. }
  409. void StartHostClient()
  410. {
  411. //Debug.Log("NetworkManager ConnectLocalClient");
  412. if (authenticator != null)
  413. {
  414. authenticator.OnStartClient();
  415. authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated);
  416. }
  417. networkAddress = "localhost";
  418. NetworkServer.ActivateHostScene();
  419. RegisterClientMessages();
  420. // ConnectLocalServer needs to be called AFTER RegisterClientMessages
  421. // (https://github.com/vis2k/Mirror/pull/1249/)
  422. NetworkClient.ConnectLocalServer();
  423. OnStartClient();
  424. }
  425. /// <summary>This stops both the client and the server that the manager is using.</summary>
  426. public void StopHost()
  427. {
  428. OnStopHost();
  429. // calling OnTransportDisconnected was needed to fix
  430. // https://github.com/vis2k/Mirror/issues/1515
  431. // so that the host client receives a DisconnectMessage
  432. // TODO reevaluate if this is still needed after all the disconnect
  433. // fixes, and try to put this into LocalConnection.Disconnect!
  434. NetworkServer.OnTransportDisconnected(NetworkConnection.LocalConnectionId);
  435. StopClient();
  436. StopServer();
  437. }
  438. /// <summary>Stops the server from listening and simulating the game.</summary>
  439. public void StopServer()
  440. {
  441. // return if already stopped to avoid recursion deadlock
  442. if (!NetworkServer.active)
  443. return;
  444. if (authenticator != null)
  445. {
  446. authenticator.OnServerAuthenticated.RemoveListener(OnServerAuthenticated);
  447. authenticator.OnStopServer();
  448. }
  449. // Get Network Manager out of DDOL before going to offline scene
  450. // to avoid collision and let a fresh Network Manager be created.
  451. // IMPORTANT: .gameObject can be null if StopClient is called from
  452. // OnApplicationQuit or from tests!
  453. #pragma warning disable 618
  454. if (gameObject != null && !PersistNetworkManagerToOfflineScene &&
  455. gameObject.scene.name == "DontDestroyOnLoad"
  456. && !string.IsNullOrEmpty(offlineScene)
  457. && SceneManager.GetActiveScene().path != offlineScene)
  458. SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene());
  459. #pragma warning restore 618
  460. OnStopServer();
  461. //Debug.Log("NetworkManager StopServer");
  462. NetworkServer.Shutdown();
  463. // set offline mode BEFORE changing scene so that FinishStartScene
  464. // doesn't think we need initialize anything.
  465. mode = NetworkManagerMode.Offline;
  466. if (!string.IsNullOrEmpty(offlineScene))
  467. {
  468. ServerChangeScene(offlineScene);
  469. }
  470. startPositionIndex = 0;
  471. networkSceneName = "";
  472. }
  473. /// <summary>Stops and disconnects the client.</summary>
  474. public void StopClient()
  475. {
  476. if (authenticator != null)
  477. {
  478. authenticator.OnClientAuthenticated.RemoveListener(OnClientAuthenticated);
  479. authenticator.OnStopClient();
  480. }
  481. // Get Network Manager out of DDOL before going to offline scene
  482. // to avoid collision and let a fresh Network Manager be created.
  483. // IMPORTANT: .gameObject can be null if StopClient is called from
  484. // OnApplicationQuit or from tests!
  485. #pragma warning disable 618
  486. if (gameObject != null && !PersistNetworkManagerToOfflineScene &&
  487. gameObject.scene.name == "DontDestroyOnLoad"
  488. && !string.IsNullOrEmpty(offlineScene)
  489. && SceneManager.GetActiveScene().path != offlineScene)
  490. SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene());
  491. #pragma warning restore 618
  492. OnStopClient();
  493. //Debug.Log("NetworkManager StopClient");
  494. // shutdown client
  495. NetworkClient.Disconnect();
  496. NetworkClient.Shutdown();
  497. // set offline mode BEFORE changing scene so that FinishStartScene
  498. // doesn't think we need initialize anything.
  499. mode = NetworkManagerMode.Offline;
  500. // If this is the host player, StopServer will already be changing scenes.
  501. // Check loadingSceneAsync to ensure we don't double-invoke the scene change.
  502. // Check if NetworkServer.active because we can get here via Disconnect before server has started to change scenes.
  503. if (!string.IsNullOrEmpty(offlineScene) && !IsSceneActive(offlineScene) && loadingSceneAsync == null && !NetworkServer.active)
  504. {
  505. ClientChangeScene(offlineScene, SceneOperation.Normal);
  506. }
  507. networkSceneName = "";
  508. }
  509. // called when quitting the application by closing the window / pressing
  510. // stop in the editor. virtual so that inheriting classes'
  511. // OnApplicationQuit() can call base.OnApplicationQuit() too
  512. public virtual void OnApplicationQuit()
  513. {
  514. // stop client first
  515. // (we want to send the quit packet to the server instead of waiting
  516. // for a timeout)
  517. if (NetworkClient.isConnected)
  518. {
  519. StopClient();
  520. //Debug.Log("OnApplicationQuit: stopped client");
  521. }
  522. // stop server after stopping client (for proper host mode stopping)
  523. if (NetworkServer.active)
  524. {
  525. StopServer();
  526. //Debug.Log("OnApplicationQuit: stopped server");
  527. }
  528. }
  529. // DEPRECATED 2021-07-21
  530. [Obsolete("Renamed to ConfigureHeadlessFrameRate()")]
  531. public virtual void ConfigureServerFrameRate() {}
  532. /// <summary>Set the frame rate for a headless builds. Override to disable or modify.</summary>
  533. // useful for dedicated servers.
  534. // useful for headless benchmark clients.
  535. public virtual void ConfigureHeadlessFrameRate()
  536. {
  537. #if UNITY_SERVER
  538. Application.targetFrameRate = serverTickRate;
  539. // Debug.Log("Server Tick Rate set to: " + Application.targetFrameRate + " Hz.");
  540. #endif
  541. // call the obsolete function in case someone did anything important
  542. #pragma warning disable 618
  543. ConfigureServerFrameRate();
  544. #pragma warning restore 618
  545. }
  546. bool InitializeSingleton()
  547. {
  548. if (singleton != null && singleton == this)
  549. return true;
  550. if (dontDestroyOnLoad)
  551. {
  552. if (singleton != null)
  553. {
  554. Debug.LogWarning("Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will be destroyed.");
  555. Destroy(gameObject);
  556. // Return false to not allow collision-destroyed second instance to continue.
  557. return false;
  558. }
  559. //Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)");
  560. singleton = this;
  561. if (Application.isPlaying) DontDestroyOnLoad(gameObject);
  562. }
  563. else
  564. {
  565. //Debug.Log("NetworkManager created singleton (ForScene)");
  566. singleton = this;
  567. }
  568. // set active transport AFTER setting singleton.
  569. // so only if we didn't destroy ourselves.
  570. Transport.activeTransport = transport;
  571. return true;
  572. }
  573. void RegisterServerMessages()
  574. {
  575. NetworkServer.OnConnectedEvent = OnServerConnectInternal;
  576. NetworkServer.OnDisconnectedEvent = OnServerDisconnect;
  577. NetworkServer.OnErrorEvent = OnServerError;
  578. NetworkServer.RegisterHandler<AddPlayerMessage>(OnServerAddPlayerInternal);
  579. // Network Server initially registers its own handler for this, so we replace it here.
  580. NetworkServer.ReplaceHandler<ReadyMessage>(OnServerReadyMessageInternal);
  581. }
  582. void RegisterClientMessages()
  583. {
  584. NetworkClient.OnConnectedEvent = OnClientConnectInternal;
  585. NetworkClient.OnDisconnectedEvent = OnClientDisconnectInternal;
  586. NetworkClient.OnErrorEvent = OnClientError;
  587. NetworkClient.RegisterHandler<NotReadyMessage>(OnClientNotReadyMessageInternal);
  588. NetworkClient.RegisterHandler<SceneMessage>(OnClientSceneInternal, false);
  589. if (playerPrefab != null)
  590. NetworkClient.RegisterPrefab(playerPrefab);
  591. foreach (GameObject prefab in spawnPrefabs.Where(t => t != null))
  592. NetworkClient.RegisterPrefab(prefab);
  593. }
  594. // This is the only way to clear the singleton, so another instance can be created.
  595. public static void Shutdown()
  596. {
  597. if (singleton == null)
  598. return;
  599. startPositions.Clear();
  600. startPositionIndex = 0;
  601. clientReadyConnection = null;
  602. singleton.StopHost();
  603. singleton = null;
  604. }
  605. // virtual so that inheriting classes' OnDestroy() can call base.OnDestroy() too
  606. public virtual void OnDestroy()
  607. {
  608. //Debug.Log("NetworkManager destroyed");
  609. }
  610. /// <summary>The name of the current network scene.</summary>
  611. // set by NetworkManager when changing the scene.
  612. // new clients will automatically load this scene.
  613. // Loading a scene manually won't set it.
  614. public static string networkSceneName { get; protected set; } = "";
  615. public static AsyncOperation loadingSceneAsync;
  616. /// <summary>Change the server scene and all client's scenes across the network.</summary>
  617. // Called automatically if onlineScene or offlineScene are set, but it
  618. // can be called from user code to switch scenes again while the game is
  619. // in progress. This automatically sets clients to be not-ready during
  620. // the change and ready again to participate in the new scene.
  621. public virtual void ServerChangeScene(string newSceneName)
  622. {
  623. if (string.IsNullOrEmpty(newSceneName))
  624. {
  625. Debug.LogError("ServerChangeScene empty scene name");
  626. return;
  627. }
  628. // Debug.Log("ServerChangeScene " + newSceneName);
  629. NetworkServer.SetAllClientsNotReady();
  630. networkSceneName = newSceneName;
  631. // Let server prepare for scene change
  632. OnServerChangeScene(newSceneName);
  633. // set server flag to stop processing messages while changing scenes
  634. // it will be re-enabled in FinishLoadScene.
  635. NetworkServer.isLoadingScene = true;
  636. StartCoroutine(loadScene(newSceneName));
  637. }
  638. IEnumerator loadScene(string newSceneName)
  639. {
  640. loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName);
  641. while (!loadingSceneAsync.isDone)
  642. {
  643. yield return null;
  644. }
  645. // ServerChangeScene can be called when stopping the server
  646. // when this happens the server is not active so does not need to tell clients about the change
  647. if (NetworkServer.active)
  648. {
  649. // notify all clients about the new scene
  650. NetworkServer.SendToAll(new SceneMessage { sceneName = newSceneName });
  651. }
  652. startPositionIndex = 0;
  653. startPositions.Clear();
  654. }
  655. // This is only set in ClientChangeScene below...never on server.
  656. // We need to check this in OnClientSceneChanged called from FinishLoadSceneClientOnly
  657. // to prevent AddPlayer message after loading/unloading additive scenes
  658. SceneOperation clientSceneOperation = SceneOperation.Normal;
  659. internal void ClientChangeScene(string newSceneName, SceneOperation sceneOperation = SceneOperation.Normal, bool customHandling = false)
  660. {
  661. if (string.IsNullOrEmpty(newSceneName))
  662. {
  663. Debug.LogError("ClientChangeScene empty scene name");
  664. return;
  665. }
  666. // Debug.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName);
  667. // Let client prepare for scene change
  668. OnClientChangeScene(newSceneName, sceneOperation, customHandling);
  669. // After calling OnClientChangeScene, exit if server since server is already doing
  670. // the actual scene change, and we don't need to do it for the host client
  671. if (NetworkServer.active)
  672. return;
  673. // set client flag to stop processing messages while loading scenes.
  674. // otherwise we would process messages and then lose all the state
  675. // as soon as the load is finishing, causing all kinds of bugs
  676. // because of missing state.
  677. // (client may be null after StopClient etc.)
  678. // Debug.Log("ClientChangeScene: pausing handlers while scene is loading to avoid data loss after scene was loaded.");
  679. NetworkClient.isLoadingScene = true;
  680. // Cache sceneOperation so we know what was requested by the
  681. // Scene message in OnClientChangeScene and OnClientSceneChanged
  682. clientSceneOperation = sceneOperation;
  683. // scene handling will happen in overrides of OnClientChangeScene and/or OnClientSceneChanged
  684. // Do not call FinishLoadScene here. Custom handler will assign loadingSceneAsync and we need
  685. // to wait for that to finish. UpdateScene already checks for that to be not null and isDone.
  686. if (customHandling)
  687. return;
  688. switch (sceneOperation)
  689. {
  690. case SceneOperation.Normal:
  691. loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName);
  692. break;
  693. case SceneOperation.LoadAdditive:
  694. // Ensure additive scene is not already loaded on client by name or path
  695. // since we don't know which was passed in the Scene message
  696. if (!SceneManager.GetSceneByName(newSceneName).IsValid() && !SceneManager.GetSceneByPath(newSceneName).IsValid())
  697. loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName, LoadSceneMode.Additive);
  698. else
  699. {
  700. Debug.LogWarning($"Scene {newSceneName} is already loaded");
  701. // Reset the flag that we disabled before entering this switch
  702. NetworkClient.isLoadingScene = false;
  703. }
  704. break;
  705. case SceneOperation.UnloadAdditive:
  706. // Ensure additive scene is actually loaded on client by name or path
  707. // since we don't know which was passed in the Scene message
  708. if (SceneManager.GetSceneByName(newSceneName).IsValid() || SceneManager.GetSceneByPath(newSceneName).IsValid())
  709. loadingSceneAsync = SceneManager.UnloadSceneAsync(newSceneName, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects);
  710. else
  711. {
  712. Debug.LogWarning($"Cannot unload {newSceneName} with UnloadAdditive operation");
  713. // Reset the flag that we disabled before entering this switch
  714. NetworkClient.isLoadingScene = false;
  715. }
  716. break;
  717. }
  718. // don't change the client's current networkSceneName when loading additive scene content
  719. if (sceneOperation == SceneOperation.Normal)
  720. networkSceneName = newSceneName;
  721. }
  722. // support additive scene loads:
  723. // NetworkScenePostProcess disables all scene objects on load, and
  724. // * NetworkServer.SpawnObjects enables them again on the server when
  725. // calling OnStartServer
  726. // * NetworkClient.PrepareToSpawnSceneObjects enables them again on the
  727. // client after the server sends ObjectSpawnStartedMessage to client
  728. // in SpawnObserversForConnection. this is only called when the
  729. // client joins, so we need to rebuild scene objects manually again
  730. // TODO merge this with FinishLoadScene()?
  731. void OnSceneLoaded(Scene scene, LoadSceneMode mode)
  732. {
  733. if (mode == LoadSceneMode.Additive)
  734. {
  735. if (NetworkServer.active)
  736. {
  737. // TODO only respawn the server objects from that scene later!
  738. NetworkServer.SpawnObjects();
  739. // Debug.Log("Respawned Server objects after additive scene load: " + scene.name);
  740. }
  741. if (NetworkClient.active)
  742. {
  743. NetworkClient.PrepareToSpawnSceneObjects();
  744. // Debug.Log("Rebuild Client spawnableObjects after additive scene load: " + scene.name);
  745. }
  746. }
  747. }
  748. void UpdateScene()
  749. {
  750. if (loadingSceneAsync != null && loadingSceneAsync.isDone)
  751. {
  752. // Debug.Log("ClientChangeScene done readyCon:" + clientReadyConnection);
  753. // try-finally to guarantee loadingSceneAsync being cleared.
  754. // fixes https://github.com/vis2k/Mirror/issues/2517 where if
  755. // FinishLoadScene throws an exception, loadingSceneAsync would
  756. // never be cleared and this code would run every Update.
  757. try
  758. {
  759. FinishLoadScene();
  760. }
  761. finally
  762. {
  763. loadingSceneAsync.allowSceneActivation = true;
  764. loadingSceneAsync = null;
  765. }
  766. }
  767. }
  768. protected void FinishLoadScene()
  769. {
  770. // NOTE: this cannot use NetworkClient.allClients[0] - that client may be for a completely different purpose.
  771. // process queued messages that we received while loading the scene
  772. Debug.Log("FinishLoadScene: resuming handlers after scene was loading.");
  773. NetworkServer.isLoadingScene = false;
  774. NetworkClient.isLoadingScene = false;
  775. // host mode?
  776. if (mode == NetworkManagerMode.Host)
  777. {
  778. FinishLoadSceneHost();
  779. }
  780. // server-only mode?
  781. else if (mode == NetworkManagerMode.ServerOnly)
  782. {
  783. FinishLoadSceneServerOnly();
  784. }
  785. // client-only mode?
  786. else if (mode == NetworkManagerMode.ClientOnly)
  787. {
  788. FinishLoadSceneClientOnly();
  789. }
  790. // otherwise we called it after stopping when loading offline scene.
  791. // do nothing then.
  792. }
  793. // finish load scene part for host mode. makes code easier and is
  794. // necessary for FinishStartHost later.
  795. // (the 3 things have to happen in that exact order)
  796. void FinishLoadSceneHost()
  797. {
  798. // debug message is very important. if we ever break anything then
  799. // it's very obvious to notice.
  800. Debug.Log("Finished loading scene in host mode.");
  801. if (clientReadyConnection != null)
  802. {
  803. OnClientConnect(clientReadyConnection);
  804. clientLoadedScene = true;
  805. clientReadyConnection = null;
  806. }
  807. // do we need to finish a StartHost() call?
  808. // then call FinishStartHost and let it take care of spawning etc.
  809. if (finishStartHostPending)
  810. {
  811. finishStartHostPending = false;
  812. FinishStartHost();
  813. // call OnServerSceneChanged
  814. OnServerSceneChanged(networkSceneName);
  815. // DO NOT call OnClientSceneChanged here.
  816. // the scene change happened because StartHost loaded the
  817. // server's online scene. it has nothing to do with the client.
  818. // this was not meant as a client scene load, so don't call it.
  819. //
  820. // otherwise AddPlayer would be called twice:
  821. // -> once for client OnConnected
  822. // -> once in OnClientSceneChanged
  823. }
  824. // otherwise we just changed a scene in host mode
  825. else
  826. {
  827. // spawn server objects
  828. NetworkServer.SpawnObjects();
  829. // call OnServerSceneChanged
  830. OnServerSceneChanged(networkSceneName);
  831. if (NetworkClient.isConnected)
  832. {
  833. // let client know that we changed scene
  834. OnClientSceneChanged(NetworkClient.connection);
  835. }
  836. }
  837. }
  838. // finish load scene part for server-only. . makes code easier and is
  839. // necessary for FinishStartServer later.
  840. void FinishLoadSceneServerOnly()
  841. {
  842. // debug message is very important. if we ever break anything then
  843. // it's very obvious to notice.
  844. Debug.Log("Finished loading scene in server-only mode.");
  845. NetworkServer.SpawnObjects();
  846. OnServerSceneChanged(networkSceneName);
  847. }
  848. // finish load scene part for client-only. makes code easier and is
  849. // necessary for FinishStartClient later.
  850. void FinishLoadSceneClientOnly()
  851. {
  852. // debug message is very important. if we ever break anything then
  853. // it's very obvious to notice.
  854. Debug.Log("Finished loading scene in client-only mode.");
  855. if (clientReadyConnection != null)
  856. {
  857. OnClientConnect(clientReadyConnection);
  858. clientLoadedScene = true;
  859. clientReadyConnection = null;
  860. }
  861. if (NetworkClient.isConnected)
  862. {
  863. OnClientSceneChanged(NetworkClient.connection);
  864. }
  865. }
  866. /// <summary>
  867. /// Registers the transform of a game object as a player spawn location.
  868. /// <para>This is done automatically by NetworkStartPosition components, but can be done manually from user script code.</para>
  869. /// </summary>
  870. /// <param name="start">Transform to register.</param>
  871. public static void RegisterStartPosition(Transform start)
  872. {
  873. // Debug.Log("RegisterStartPosition: (" + start.gameObject.name + ") " + start.position);
  874. startPositions.Add(start);
  875. // reorder the list so that round-robin spawning uses the start positions
  876. // in hierarchy order. This assumes all objects with NetworkStartPosition
  877. // component are siblings, either in the scene root or together as children
  878. // under a single parent in the scene.
  879. startPositions = startPositions.OrderBy(transform => transform.GetSiblingIndex()).ToList();
  880. }
  881. /// <summary>Unregister a Transform from start positions.</summary>
  882. // TODO why is this static?
  883. public static void UnRegisterStartPosition(Transform start)
  884. {
  885. // Debug.Log("UnRegisterStartPosition: (" + start.gameObject.name + ") " + start.position);
  886. startPositions.Remove(start);
  887. }
  888. /// <summary>Get the next NetworkStartPosition based on the selected PlayerSpawnMethod.</summary>
  889. public Transform GetStartPosition()
  890. {
  891. // first remove any dead transforms
  892. startPositions.RemoveAll(t => t == null);
  893. if (startPositions.Count == 0)
  894. return null;
  895. if (playerSpawnMethod == PlayerSpawnMethod.Random)
  896. {
  897. return startPositions[UnityEngine.Random.Range(0, startPositions.Count)];
  898. }
  899. else
  900. {
  901. Transform startPosition = startPositions[startPositionIndex];
  902. startPositionIndex = (startPositionIndex + 1) % startPositions.Count;
  903. return startPosition;
  904. }
  905. }
  906. void OnServerConnectInternal(NetworkConnection conn)
  907. {
  908. //Debug.Log("NetworkManager.OnServerConnectInternal");
  909. if (authenticator != null)
  910. {
  911. // we have an authenticator - let it handle authentication
  912. authenticator.OnServerAuthenticate(conn);
  913. }
  914. else
  915. {
  916. // authenticate immediately
  917. OnServerAuthenticated(conn);
  918. }
  919. }
  920. // called after successful authentication
  921. // TODO do the NetworkServer.OnAuthenticated thing from x branch
  922. void OnServerAuthenticated(NetworkConnection conn)
  923. {
  924. //Debug.Log("NetworkManager.OnServerAuthenticated");
  925. // set connection to authenticated
  926. conn.isAuthenticated = true;
  927. // proceed with the login handshake by calling OnServerConnect
  928. if (networkSceneName != "" && networkSceneName != offlineScene)
  929. {
  930. SceneMessage msg = new SceneMessage() { sceneName = networkSceneName };
  931. conn.Send(msg);
  932. }
  933. OnServerConnect(conn);
  934. }
  935. void OnServerReadyMessageInternal(NetworkConnection conn, ReadyMessage msg)
  936. {
  937. //Debug.Log("NetworkManager.OnServerReadyMessageInternal");
  938. OnServerReady(conn);
  939. }
  940. void OnServerAddPlayerInternal(NetworkConnection conn, AddPlayerMessage msg)
  941. {
  942. //Debug.Log("NetworkManager.OnServerAddPlayer");
  943. if (autoCreatePlayer && playerPrefab == null)
  944. {
  945. Debug.LogError("The PlayerPrefab is empty on the NetworkManager. Please setup a PlayerPrefab object.");
  946. return;
  947. }
  948. if (autoCreatePlayer && playerPrefab.GetComponent<NetworkIdentity>() == null)
  949. {
  950. Debug.LogError("The PlayerPrefab does not have a NetworkIdentity. Please add a NetworkIdentity to the player prefab.");
  951. return;
  952. }
  953. if (conn.identity != null)
  954. {
  955. Debug.LogError("There is already a player for this connection.");
  956. return;
  957. }
  958. OnServerAddPlayer(conn);
  959. }
  960. void OnClientConnectInternal()
  961. {
  962. //Debug.Log("NetworkManager.OnClientConnectInternal");
  963. if (authenticator != null)
  964. {
  965. // we have an authenticator - let it handle authentication
  966. authenticator.OnClientAuthenticate();
  967. }
  968. else
  969. {
  970. // authenticate immediately
  971. OnClientAuthenticated(NetworkClient.connection);
  972. }
  973. }
  974. // called after successful authentication
  975. void OnClientAuthenticated(NetworkConnection conn)
  976. {
  977. //Debug.Log("NetworkManager.OnClientAuthenticated");
  978. // set connection to authenticated
  979. conn.isAuthenticated = true;
  980. // proceed with the login handshake by calling OnClientConnect
  981. if (string.IsNullOrEmpty(onlineScene) || onlineScene == offlineScene || IsSceneActive(onlineScene))
  982. {
  983. clientLoadedScene = false;
  984. OnClientConnect(conn);
  985. }
  986. else
  987. {
  988. // will wait for scene id to come from the server.
  989. clientLoadedScene = true;
  990. clientReadyConnection = conn;
  991. }
  992. }
  993. // TODO call OnClientDisconnect directly, don't pass the connection
  994. void OnClientDisconnectInternal()
  995. {
  996. //Debug.Log("NetworkManager.OnClientDisconnectInternal");
  997. OnClientDisconnect(NetworkClient.connection);
  998. }
  999. void OnClientNotReadyMessageInternal(NotReadyMessage msg)
  1000. {
  1001. //Debug.Log("NetworkManager.OnClientNotReadyMessageInternal");
  1002. NetworkClient.ready = false;
  1003. OnClientNotReady(NetworkClient.connection);
  1004. // NOTE: clientReadyConnection is not set here! don't want OnClientConnect to be invoked again after scene changes.
  1005. }
  1006. void OnClientSceneInternal(SceneMessage msg)
  1007. {
  1008. //Debug.Log("NetworkManager.OnClientSceneInternal");
  1009. // This needs to run for host client too. NetworkServer.active is checked there
  1010. if (NetworkClient.isConnected)
  1011. {
  1012. ClientChangeScene(msg.sceneName, msg.sceneOperation, msg.customHandling);
  1013. }
  1014. }
  1015. /// <summary>Called on the server when a new client connects.</summary>
  1016. public virtual void OnServerConnect(NetworkConnection conn) {}
  1017. /// <summary>Called on the server when a client disconnects.</summary>
  1018. // Called by NetworkServer.OnTransportDisconnect!
  1019. public virtual void OnServerDisconnect(NetworkConnection conn)
  1020. {
  1021. // by default, this function destroys the connection's player.
  1022. // can be overwritten for cases like delayed logouts in MMOs to
  1023. // avoid players escaping from PvP situations by logging out.
  1024. NetworkServer.DestroyPlayerForConnection(conn);
  1025. //Debug.Log("OnServerDisconnect: Client disconnected.");
  1026. }
  1027. /// <summary>Called on the server when a client is ready (= loaded the scene)</summary>
  1028. public virtual void OnServerReady(NetworkConnection conn)
  1029. {
  1030. if (conn.identity == null)
  1031. {
  1032. // this is now allowed (was not for a while)
  1033. //Debug.Log("Ready with no player object");
  1034. }
  1035. NetworkServer.SetClientReady(conn);
  1036. }
  1037. /// <summary>Called on server when a client requests to add the player. Adds playerPrefab by default. Can be overwritten.</summary>
  1038. // The default implementation for this function creates a new player object from the playerPrefab.
  1039. public virtual void OnServerAddPlayer(NetworkConnection conn)
  1040. {
  1041. Transform startPos = GetStartPosition();
  1042. GameObject player = startPos != null
  1043. ? Instantiate(playerPrefab, startPos.position, startPos.rotation)
  1044. : Instantiate(playerPrefab);
  1045. // instantiating a "Player" prefab gives it the name "Player(clone)"
  1046. // => appending the connectionId is WAY more useful for debugging!
  1047. player.name = $"{playerPrefab.name} [connId={conn.connectionId}]";
  1048. NetworkServer.AddPlayerForConnection(conn, player);
  1049. }
  1050. // Deprecated 2021-02-13
  1051. [Obsolete("OnServerError was removed because it hasn't been used in a long time.")]
  1052. public virtual void OnServerError(NetworkConnection conn, int errorCode) {}
  1053. /// <summary>Called on server when transport raises an exception. NetworkConnection may be null.</summary>
  1054. public virtual void OnServerError(NetworkConnection conn, Exception exception) {}
  1055. /// <summary>Called from ServerChangeScene immediately before SceneManager.LoadSceneAsync is executed</summary>
  1056. public virtual void OnServerChangeScene(string newSceneName) {}
  1057. /// <summary>Called on server after a scene load with ServerChangeScene() is completed.</summary>
  1058. public virtual void OnServerSceneChanged(string sceneName) {}
  1059. /// <summary>Called on the client when connected to a server. By default it sets client as ready and adds a player.</summary>
  1060. // TODO client only ever uses NetworkClient.connection. this parameter is redundant.
  1061. public virtual void OnClientConnect(NetworkConnection conn)
  1062. {
  1063. // OnClientConnect by default calls AddPlayer but it should not do
  1064. // that when we have online/offline scenes. so we need the
  1065. // clientLoadedScene flag to prevent it.
  1066. if (!clientLoadedScene)
  1067. {
  1068. // Ready/AddPlayer is usually triggered by a scene load
  1069. // completing. if no scene was loaded, then Ready/AddPlayer it
  1070. // here instead.
  1071. if (!NetworkClient.ready) NetworkClient.Ready();
  1072. if (autoCreatePlayer)
  1073. {
  1074. NetworkClient.AddPlayer();
  1075. }
  1076. }
  1077. }
  1078. /// <summary>Called on clients when disconnected from a server.</summary>
  1079. // TODO client only ever uses NetworkClient.connection. this parameter is redundant.
  1080. public virtual void OnClientDisconnect(NetworkConnection conn)
  1081. {
  1082. StopClient();
  1083. }
  1084. // Deprecated 2021-02-13
  1085. [Obsolete("OnClientError was removed because it hasn't been used in a long time.")]
  1086. public virtual void OnClientError(NetworkConnection conn, int errorCode) {}
  1087. /// <summary>Called on client when transport raises an exception.</summary>
  1088. public virtual void OnClientError(Exception exception) {}
  1089. /// <summary>Called on clients when a servers tells the client it is no longer ready, e.g. when switching scenes.</summary>
  1090. // TODO client only ever uses NetworkClient.connection. this parameter is redundant.
  1091. public virtual void OnClientNotReady(NetworkConnection conn) {}
  1092. /// <summary>Called from ClientChangeScene immediately before SceneManager.LoadSceneAsync is executed</summary>
  1093. // customHandling: indicates if scene loading will be handled through overrides
  1094. public virtual void OnClientChangeScene(string newSceneName, SceneOperation sceneOperation, bool customHandling) {}
  1095. /// <summary>Called on clients when a scene has completed loaded, when the scene load was initiated by the server.</summary>
  1096. // Scene changes can cause player objects to be destroyed. The default
  1097. // implementation of OnClientSceneChanged in the NetworkManager is to
  1098. // add a player object for the connection if no player object exists.
  1099. // TODO client only ever uses NetworkClient.connection. this parameter is redundant.
  1100. public virtual void OnClientSceneChanged(NetworkConnection conn)
  1101. {
  1102. // always become ready.
  1103. if (!NetworkClient.ready) NetworkClient.Ready();
  1104. // Only call AddPlayer for normal scene changes, not additive load/unload
  1105. if (clientSceneOperation == SceneOperation.Normal && autoCreatePlayer && NetworkClient.localPlayer == null)
  1106. {
  1107. // add player if existing one is null
  1108. NetworkClient.AddPlayer();
  1109. }
  1110. }
  1111. // Since there are multiple versions of StartServer, StartClient and
  1112. // StartHost, to reliably customize their functionality, users would
  1113. // need override all the versions. Instead these callbacks are invoked
  1114. // from all versions, so users only need to implement this one case.
  1115. /// <summary>This is invoked when a host is started.</summary>
  1116. public virtual void OnStartHost() {}
  1117. /// <summary>This is invoked when a server is started - including when a host is started.</summary>
  1118. public virtual void OnStartServer() {}
  1119. /// <summary>This is invoked when the client is started.</summary>
  1120. public virtual void OnStartClient() {}
  1121. /// <summary>This is called when a server is stopped - including when a host is stopped.</summary>
  1122. public virtual void OnStopServer() {}
  1123. /// <summary>This is called when a client is stopped.</summary>
  1124. public virtual void OnStopClient() {}
  1125. /// <summary>This is called when a host is stopped.</summary>
  1126. public virtual void OnStopHost() {}
  1127. }
  1128. }