Mirror Networking
Mirror.NetworkManager Class Reference
Inheritance diagram for Mirror.NetworkManager:

Public Member Functions

virtual void OnValidate ()
 
virtual void Reset ()
 
virtual void Awake ()
 
virtual void Start ()
 
virtual void LateUpdate ()
 
void StartServer ()
 Starts the server, listening for incoming connections. More...
 
void StartClient ()
 Starts the client, connects it to the server with networkAddress. More...
 
void StartClient (Uri uri)
 Starts the client, connects it to the server via Uri More...
 
void StartHost ()
 Starts a network "host" - a server and client in the same application. More...
 
void StopHost ()
 This stops both the client and the server that the manager is using. More...
 
void StopServer ()
 Stops the server from listening and simulating the game. More...
 
void StopClient ()
 Stops and disconnects the client. More...
 
virtual void OnApplicationQuit ()
 
virtual void ConfigureHeadlessFrameRate ()
 Set the frame rate for a headless builds. Override to disable or modify. More...
 
virtual void OnDestroy ()
 
virtual void ServerChangeScene (string newSceneName)
 Change the server scene and all client's scenes across the network. More...
 
Transform GetStartPosition ()
 Get the next NetworkStartPosition based on the selected PlayerSpawnMethod. More...
 
virtual void OnServerConnect (NetworkConnectionToClient conn)
 Called on the server when a new client connects. More...
 
virtual void OnServerDisconnect (NetworkConnectionToClient conn)
 Called on the server when a client disconnects. More...
 
virtual void OnServerReady (NetworkConnectionToClient conn)
 Called on the server when a client is ready (= loaded the scene) More...
 
virtual void OnServerAddPlayer (NetworkConnectionToClient conn)
 Called on server when a client requests to add the player. Adds playerPrefab by default. Can be overwritten. More...
 
virtual void OnServerError (NetworkConnectionToClient conn, Exception exception)
 
virtual void OnServerError (NetworkConnectionToClient conn, TransportError error, string reason)
 Called on server when transport raises an exception. NetworkConnection may be null. More...
 
virtual void OnServerChangeScene (string newSceneName)
 Called from ServerChangeScene immediately before SceneManager.LoadSceneAsync is executed More...
 
virtual void OnServerSceneChanged (string sceneName)
 Called on server after a scene load with ServerChangeScene() is completed. More...
 
virtual void OnClientConnect ()
 Called on the client when connected to a server. By default it sets client as ready and adds a player. More...
 
virtual void OnClientDisconnect ()
 Called on clients when disconnected from a server. More...
 
virtual void OnClientError (Exception exception)
 
virtual void OnClientError (TransportError error, string reason)
 Called on client when transport raises an exception. More...
 
virtual void OnClientNotReady ()
 Called on clients when a servers tells the client it is no longer ready, e.g. when switching scenes. More...
 
virtual void OnClientChangeScene (string newSceneName, SceneOperation sceneOperation, bool customHandling)
 Called from ClientChangeScene immediately before SceneManager.LoadSceneAsync is executed More...
 
virtual void OnClientSceneChanged ()
 Called on clients when a scene has completed loaded, when the scene load was initiated by the server. More...
 
virtual void OnStartHost ()
 This is invoked when a host is started. More...
 
virtual void OnStartServer ()
 This is invoked when a server is started - including when a host is started. More...
 
virtual void OnStartClient ()
 This is invoked when the client is started. More...
 
virtual void OnStopServer ()
 This is called when a server is stopped - including when a host is stopped. More...
 
virtual void OnStopClient ()
 This is called when a client is stopped. More...
 
virtual void OnStopHost ()
 This is called when a host is stopped. More...
 

Static Public Member Functions

static bool IsSceneActive (string scene)
 
static void ResetStatics ()
 
static void RegisterStartPosition (Transform start)
 Registers the transform of a game object as a player spawn location. More...
 
static void UnRegisterStartPosition (Transform start)
 Unregister a Transform from start positions. More...
 

Public Attributes

bool dontDestroyOnLoad = true
 Enable to keep NetworkManager alive when changing scenes. More...
 
bool runInBackground = true
 Multiplayer games should always run in the background so the network doesn't time out. More...
 
bool autoStartServerBuild = true
 Should the server auto-start when 'Server Build' is checked in build settings More...
 
int serverTickRate = 30
 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. More...
 
string offlineScene = ""
 Automatically switch to this scene upon going offline (on start / on disconnect / on shutdown). More...
 
string onlineScene = ""
 Automatically switch to this scene upon going online (after connect/startserver). More...
 
string networkAddress = "localhost"
 Server's address for clients to connect to. More...
 
int maxConnections = 100
 The maximum number of concurrent network connections to support. More...
 
NetworkAuthenticator authenticator
 
GameObject playerPrefab
 The default prefab to be used to create player objects on the server. More...
 
bool autoCreatePlayer = true
 Enable to automatically create player objects on connect and on scene change. More...
 
PlayerSpawnMethod playerSpawnMethod
 Where to spawn players. More...
 
List< GameObject > spawnPrefabs = new List<GameObject>()
 Prefabs that can be spawned over the network need to be registered here. More...
 

Static Public Attributes

static List< Transform > startPositions = new List<Transform>()
 List of transforms populated by NetworkStartPositions More...
 
static int startPositionIndex
 
static AsyncOperation loadingSceneAsync
 

Protected Member Functions

void FinishLoadScene ()
 

Protected Attributes

Transport transport
 
bool clientLoadedScene
 True if the client loaded a new scene when connecting to the server. More...
 

Properties

static NetworkManager singleton [get, set]
 The one and only NetworkManager More...
 
int numPlayers [get]
 Number of active player objects across all connections on the server. More...
 
bool isNetworkActive [get]
 True if the server is running or client is connected/connecting. More...
 
NetworkManagerMode mode [get]
 
static string networkSceneName = "" [get, protected set]
 The name of the current network scene. More...
 

Detailed Description

Definition at line 17 of file NetworkManager.cs.

Member Function Documentation

◆ Awake()

virtual void Mirror.NetworkManager.Awake ( )
virtual

Definition at line 185 of file NetworkManager.cs.

186 {
187 // Don't allow collision-destroyed second instance to continue.
188 if (!InitializeSingleton()) return;
189
190 Debug.Log("Mirror | mirror-networking.com | discord.gg/N9QVxbM");
191
192 // Set the networkSceneName to prevent a scene reload
193 // if client connection to server fails.
195
196 // setup OnSceneLoaded callback
197 SceneManager.sceneLoaded += OnSceneLoaded;
198 }
static string networkSceneName
The name of the current network scene.
string offlineScene
Automatically switch to this scene upon going offline (on start / on disconnect / on shutdown).

◆ ConfigureHeadlessFrameRate()

virtual void Mirror.NetworkManager.ConfigureHeadlessFrameRate ( )
virtual

Set the frame rate for a headless builds. Override to disable or modify.

Definition at line 642 of file NetworkManager.cs.

643 {
644#if UNITY_SERVER
645 Application.targetFrameRate = serverTickRate;
646 // Debug.Log($"Server Tick Rate set to {Application.targetFrameRate} Hz.");
647#endif
648 }
int serverTickRate
Server Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to mini...

◆ FinishLoadScene()

void Mirror.NetworkManager.FinishLoadScene ( )
protected

Definition at line 919 of file NetworkManager.cs.

920 {
921 // NOTE: this cannot use NetworkClient.allClients[0] - that client may be for a completely different purpose.
922
923 // process queued messages that we received while loading the scene
924 //Debug.Log("FinishLoadScene: resuming handlers after scene was loading.");
925 NetworkServer.isLoadingScene = false;
926 NetworkClient.isLoadingScene = false;
927
928 // host mode?
929 if (mode == NetworkManagerMode.Host)
930 {
931 FinishLoadSceneHost();
932 }
933 // server-only mode?
934 else if (mode == NetworkManagerMode.ServerOnly)
935 {
936 FinishLoadSceneServerOnly();
937 }
938 // client-only mode?
939 else if (mode == NetworkManagerMode.ClientOnly)
940 {
941 FinishLoadSceneClientOnly();
942 }
943 // otherwise we called it after stopping when loading offline scene.
944 // do nothing then.
945 }

◆ GetStartPosition()

Transform Mirror.NetworkManager.GetStartPosition ( )

Get the next NetworkStartPosition based on the selected PlayerSpawnMethod.

Definition at line 1056 of file NetworkManager.cs.

1057 {
1058 // first remove any dead transforms
1059 startPositions.RemoveAll(t => t == null);
1060
1061 if (startPositions.Count == 0)
1062 return null;
1063
1064 if (playerSpawnMethod == PlayerSpawnMethod.Random)
1065 {
1066 return startPositions[UnityEngine.Random.Range(0, startPositions.Count)];
1067 }
1068 else
1069 {
1070 Transform startPosition = startPositions[startPositionIndex];
1071 startPositionIndex = (startPositionIndex + 1) % startPositions.Count;
1072 return startPosition;
1073 }
1074 }
static List< Transform > startPositions
List of transforms populated by NetworkStartPositions
PlayerSpawnMethod playerSpawnMethod
Where to spawn players.

◆ IsSceneActive()

static bool Mirror.NetworkManager.IsSceneActive ( string  scene)
static

Definition at line 229 of file NetworkManager.cs.

230 {
231 Scene activeScene = SceneManager.GetActiveScene();
232 return activeScene.path == scene || activeScene.name == scene;
233 }

◆ LateUpdate()

virtual void Mirror.NetworkManager.LateUpdate ( )
virtual

Definition at line 217 of file NetworkManager.cs.

218 {
219 UpdateScene();
220 }

◆ OnApplicationQuit()

virtual void Mirror.NetworkManager.OnApplicationQuit ( )
virtual

Definition at line 617 of file NetworkManager.cs.

618 {
619 // stop client first
620 // (we want to send the quit packet to the server instead of waiting
621 // for a timeout)
622 if (NetworkClient.isConnected)
623 {
624 StopClient();
625 //Debug.Log("OnApplicationQuit: stopped client");
626 }
627
628 // stop server after stopping client (for proper host mode stopping)
629 if (NetworkServer.active)
630 {
631 StopServer();
632 //Debug.Log("OnApplicationQuit: stopped server");
633 }
634
635 // Call ResetStatics to reset statics and singleton
636 ResetStatics();
637 }
void StopServer()
Stops the server from listening and simulating the game.
void StopClient()
Stops and disconnects the client.

◆ OnClientChangeScene()

virtual void Mirror.NetworkManager.OnClientChangeScene ( string  newSceneName,
SceneOperation  sceneOperation,
bool  customHandling 
)
virtual

Called from ClientChangeScene immediately before SceneManager.LoadSceneAsync is executed

Definition at line 1306 of file NetworkManager.cs.

1306{}

◆ OnClientConnect()

virtual void Mirror.NetworkManager.OnClientConnect ( )
virtual

Called on the client when connected to a server. By default it sets client as ready and adds a player.

Definition at line 1264 of file NetworkManager.cs.

1265 {
1266 // OnClientConnect by default calls AddPlayer but it should not do
1267 // that when we have online/offline scenes. so we need the
1268 // clientLoadedScene flag to prevent it.
1269 if (!clientLoadedScene)
1270 {
1271 // Ready/AddPlayer is usually triggered by a scene load completing.
1272 // if no scene was loaded, then Ready/AddPlayer it here instead.
1273 if (!NetworkClient.ready)
1274 NetworkClient.Ready();
1275
1276 if (autoCreatePlayer)
1277 NetworkClient.AddPlayer();
1278 }
1279 }
bool autoCreatePlayer
Enable to automatically create player objects on connect and on scene change.
bool clientLoadedScene
True if the client loaded a new scene when connecting to the server.

◆ OnClientDisconnect()

virtual void Mirror.NetworkManager.OnClientDisconnect ( )
virtual

Called on clients when disconnected from a server.

Definition at line 1282 of file NetworkManager.cs.

1283 {
1284 if (mode == NetworkManagerMode.Offline)
1285 return;
1286
1287 StopClient();
1288 }

◆ OnClientError() [1/2]

virtual void Mirror.NetworkManager.OnClientError ( Exception  exception)
virtual

Definition at line 1292 of file NetworkManager.cs.

1292{}

◆ OnClientError() [2/2]

virtual void Mirror.NetworkManager.OnClientError ( TransportError  error,
string  reason 
)
virtual

Called on client when transport raises an exception.

Definition at line 1294 of file NetworkManager.cs.

1295 {
1296#pragma warning disable CS0618
1297 OnClientError(new Exception(reason));
1298#pragma warning restore CS0618
1299 }

◆ OnClientNotReady()

virtual void Mirror.NetworkManager.OnClientNotReady ( )
virtual

Called on clients when a servers tells the client it is no longer ready, e.g. when switching scenes.

Definition at line 1302 of file NetworkManager.cs.

1302{}

◆ OnClientSceneChanged()

virtual void Mirror.NetworkManager.OnClientSceneChanged ( )
virtual

Called on clients when a scene has completed loaded, when the scene load was initiated by the server.

Definition at line 1312 of file NetworkManager.cs.

1313 {
1314 // always become ready.
1315 if (!NetworkClient.ready) NetworkClient.Ready();
1316
1317 // Only call AddPlayer for normal scene changes, not additive load/unload
1318 if (clientSceneOperation == SceneOperation.Normal && autoCreatePlayer && NetworkClient.localPlayer == null)
1319 {
1320 // add player if existing one is null
1321 NetworkClient.AddPlayer();
1322 }
1323 }

◆ OnDestroy()

virtual void Mirror.NetworkManager.OnDestroy ( )
virtual

Definition at line 734 of file NetworkManager.cs.

735 {
736 //Debug.Log("NetworkManager destroyed");
737 }

◆ OnServerAddPlayer()

virtual void Mirror.NetworkManager.OnServerAddPlayer ( NetworkConnectionToClient  conn)
virtual

Called on server when a client requests to add the player. Adds playerPrefab by default. Can be overwritten.

Definition at line 1233 of file NetworkManager.cs.

1234 {
1235 Transform startPos = GetStartPosition();
1236 GameObject player = startPos != null
1237 ? Instantiate(playerPrefab, startPos.position, startPos.rotation)
1238 : Instantiate(playerPrefab);
1239
1240 // instantiating a "Player" prefab gives it the name "Player(clone)"
1241 // => appending the connectionId is WAY more useful for debugging!
1242 player.name = $"{playerPrefab.name} [connId={conn.connectionId}]";
1243 NetworkServer.AddPlayerForConnection(conn, player);
1244 }
Transform GetStartPosition()
Get the next NetworkStartPosition based on the selected PlayerSpawnMethod.
GameObject playerPrefab
The default prefab to be used to create player objects on the server.

◆ OnServerChangeScene()

virtual void Mirror.NetworkManager.OnServerChangeScene ( string  newSceneName)
virtual

Called from ServerChangeScene immediately before SceneManager.LoadSceneAsync is executed

Definition at line 1258 of file NetworkManager.cs.

1258{}

◆ OnServerConnect()

virtual void Mirror.NetworkManager.OnServerConnect ( NetworkConnectionToClient  conn)
virtual

Called on the server when a new client connects.

Definition at line 1207 of file NetworkManager.cs.

1207{}

◆ OnServerDisconnect()

virtual void Mirror.NetworkManager.OnServerDisconnect ( NetworkConnectionToClient  conn)
virtual

Called on the server when a client disconnects.

Definition at line 1211 of file NetworkManager.cs.

1212 {
1213 // by default, this function destroys the connection's player.
1214 // can be overwritten for cases like delayed logouts in MMOs to
1215 // avoid players escaping from PvP situations by logging out.
1216 NetworkServer.DestroyPlayerForConnection(conn);
1217 //Debug.Log("OnServerDisconnect: Client disconnected.");
1218 }

◆ OnServerError() [1/2]

virtual void Mirror.NetworkManager.OnServerError ( NetworkConnectionToClient  conn,
Exception  exception 
)
virtual

Definition at line 1248 of file NetworkManager.cs.

1248{}

◆ OnServerError() [2/2]

virtual void Mirror.NetworkManager.OnServerError ( NetworkConnectionToClient  conn,
TransportError  error,
string  reason 
)
virtual

Called on server when transport raises an exception. NetworkConnection may be null.

Definition at line 1250 of file NetworkManager.cs.

1251 {
1252#pragma warning disable CS0618
1253 OnServerError(conn, new Exception(reason));
1254#pragma warning restore CS0618
1255 }

◆ OnServerReady()

virtual void Mirror.NetworkManager.OnServerReady ( NetworkConnectionToClient  conn)
virtual

Called on the server when a client is ready (= loaded the scene)

Definition at line 1221 of file NetworkManager.cs.

1222 {
1223 if (conn.identity == null)
1224 {
1225 // this is now allowed (was not for a while)
1226 //Debug.Log("Ready with no player object");
1227 }
1228 NetworkServer.SetClientReady(conn);
1229 }

◆ OnServerSceneChanged()

virtual void Mirror.NetworkManager.OnServerSceneChanged ( string  sceneName)
virtual

Called on server after a scene load with ServerChangeScene() is completed.

Definition at line 1261 of file NetworkManager.cs.

1261{}

◆ OnStartClient()

virtual void Mirror.NetworkManager.OnStartClient ( )
virtual

This is invoked when the client is started.

Definition at line 1337 of file NetworkManager.cs.

1337{}

◆ OnStartHost()

virtual void Mirror.NetworkManager.OnStartHost ( )
virtual

This is invoked when a host is started.

Definition at line 1331 of file NetworkManager.cs.

1331{}

◆ OnStartServer()

virtual void Mirror.NetworkManager.OnStartServer ( )
virtual

This is invoked when a server is started - including when a host is started.

Definition at line 1334 of file NetworkManager.cs.

1334{}

◆ OnStopClient()

virtual void Mirror.NetworkManager.OnStopClient ( )
virtual

This is called when a client is stopped.

Definition at line 1343 of file NetworkManager.cs.

1343{}

◆ OnStopHost()

virtual void Mirror.NetworkManager.OnStopHost ( )
virtual

This is called when a host is stopped.

Definition at line 1346 of file NetworkManager.cs.

1346{}

◆ OnStopServer()

virtual void Mirror.NetworkManager.OnStopServer ( )
virtual

This is called when a server is stopped - including when a host is stopped.

Definition at line 1340 of file NetworkManager.cs.

1340{}

◆ OnValidate()

virtual void Mirror.NetworkManager.OnValidate ( )
virtual

Definition at line 126 of file NetworkManager.cs.

127 {
128 // always >= 0
129 maxConnections = Mathf.Max(maxConnections, 0);
130
131 if (playerPrefab != null && playerPrefab.GetComponent<NetworkIdentity>() == null)
132 {
133 Debug.LogError("NetworkManager - Player Prefab must have a NetworkIdentity.");
134 playerPrefab = null;
135 }
136
137 // This avoids the mysterious "Replacing existing prefab with assetId ... Old prefab 'Player', New prefab 'Player'" warning.
138 if (playerPrefab != null && spawnPrefabs.Contains(playerPrefab))
139 {
140 Debug.LogWarning("NetworkManager - Player Prefab should not be added to Registered Spawnable Prefabs list...removed it.");
142 }
143 }
List< GameObject > spawnPrefabs
Prefabs that can be spawned over the network need to be registered here.
int maxConnections
The maximum number of concurrent network connections to support.

◆ RegisterStartPosition()

static void Mirror.NetworkManager.RegisterStartPosition ( Transform  start)
static

Registers the transform of a game object as a player spawn location.

This is done automatically by NetworkStartPosition components, but can be done manually from user script code.

Parameters
startTransform to register.

Definition at line 1034 of file NetworkManager.cs.

1035 {
1036 // Debug.Log($"RegisterStartPosition: {start.gameObject.name} {start.position}");
1037 startPositions.Add(start);
1038
1039 // reorder the list so that round-robin spawning uses the start positions
1040 // in hierarchy order. This assumes all objects with NetworkStartPosition
1041 // component are siblings, either in the scene root or together as children
1042 // under a single parent in the scene.
1043 startPositions = startPositions.OrderBy(transform => transform.GetSiblingIndex()).ToList();
1044 }

◆ Reset()

virtual void Mirror.NetworkManager.Reset ( )
virtual

Definition at line 149 of file NetworkManager.cs.

150 {
151 // make sure someone doesn't accidentally add another NetworkManager
152 // need transform.root because when adding to a child, the parent's
153 // Reset isn't called.
154 foreach (NetworkManager manager in transform.root.GetComponentsInChildren<NetworkManager>())
155 {
156 if (manager != this)
157 {
158 Debug.LogError($"{name} detected another component of type {typeof(NetworkManager)} in its hierarchy on {manager.name}. There can only be one, please remove one of them.");
159 // return early so that transport component isn't auto-added
160 // to the duplicate NetworkManager.
161 return;
162 }
163 }
164
165 // add transport if there is none yet. makes upgrading easier.
166 if (transport == null)
167 {
168#if UNITY_EDITOR
169 // RecordObject needs to be called before we make the change
170 UnityEditor.Undo.RecordObject(gameObject, "Added default Transport");
171#endif
172
173 transport = GetComponent<Transport>();
174
175 // was a transport added yet? if not, add one
176 if (transport == null)
177 {
178 transport = gameObject.AddComponent<KcpTransport>();
179 Debug.Log("NetworkManager: added default Transport because there was none yet.");
180 }
181 }
182 }

◆ ResetStatics()

static void Mirror.NetworkManager.ResetStatics ( )
static

Definition at line 716 of file NetworkManager.cs.

717 {
718 // call StopHost if we have a singleton
719 if (singleton)
721
722 // reset all statics
723 startPositions.Clear();
724 startPositionIndex = 0;
725 clientReadyConnection = null;
726 loadingSceneAsync = null;
727 networkSceneName = string.Empty;
728
729 // and finally (in case it isn't null already)...
730 singleton = null;
731 }
static NetworkManager singleton
The one and only NetworkManager
void StopHost()
This stops both the client and the server that the manager is using.

◆ ServerChangeScene()

virtual void Mirror.NetworkManager.ServerChangeScene ( string  newSceneName)
virtual

Change the server scene and all client's scenes across the network.

Definition at line 752 of file NetworkManager.cs.

753 {
754 if (string.IsNullOrWhiteSpace(newSceneName))
755 {
756 Debug.LogError("ServerChangeScene empty scene name");
757 return;
758 }
759
760 if (NetworkServer.isLoadingScene && newSceneName == networkSceneName)
761 {
762 Debug.LogError($"Scene change is already in progress for {newSceneName}");
763 return;
764 }
765
766 // Debug.Log($"ServerChangeScene {newSceneName}");
767 NetworkServer.SetAllClientsNotReady();
768 networkSceneName = newSceneName;
769
770 // Let server prepare for scene change
771 OnServerChangeScene(newSceneName);
772
773 // set server flag to stop processing messages while changing scenes
774 // it will be re-enabled in FinishLoadScene.
775 NetworkServer.isLoadingScene = true;
776
777 loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName);
778
779 // ServerChangeScene can be called when stopping the server
780 // when this happens the server is not active so does not need to tell clients about the change
781 if (NetworkServer.active)
782 {
783 // notify all clients about the new scene
784 NetworkServer.SendToAll(new SceneMessage { sceneName = newSceneName });
785 }
786
787 startPositionIndex = 0;
788 startPositions.Clear();
789 }
virtual void OnServerChangeScene(string newSceneName)
Called from ServerChangeScene immediately before SceneManager.LoadSceneAsync is executed

◆ Start()

virtual void Mirror.NetworkManager.Start ( )
virtual

Definition at line 201 of file NetworkManager.cs.

202 {
203 // headless mode? then start the server
204 // can't do this in Awake because Awake is for initialization.
205 // some transports might not be ready until Start.
206 //
207 // (tick rate is applied in StartServer!)
208#if UNITY_SERVER
210 {
211 StartServer();
212 }
213#endif
214 }
bool autoStartServerBuild
Should the server auto-start when 'Server Build' is checked in build settings
void StartServer()
Starts the server, listening for incoming connections.

◆ StartClient() [1/2]

void Mirror.NetworkManager.StartClient ( )

Starts the client, connects it to the server with networkAddress.

Definition at line 311 of file NetworkManager.cs.

312 {
313 if (NetworkClient.active)
314 {
315 Debug.LogWarning("Client already started.");
316 return;
317 }
318
319 mode = NetworkManagerMode.ClientOnly;
320
321 InitializeSingleton();
322
323 if (runInBackground)
324 Application.runInBackground = true;
325
326 if (authenticator != null)
327 {
328 authenticator.OnStartClient();
329 authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated);
330 }
331
332 // In case this is a headless client...
334
335 RegisterClientMessages();
336
337 if (string.IsNullOrWhiteSpace(networkAddress))
338 {
339 Debug.LogError("Must set the Network Address field in the manager");
340 return;
341 }
342 // Debug.Log($"NetworkManager StartClient address:{networkAddress}");
343
344 NetworkClient.Connect(networkAddress);
345
347 }
UnityEvent OnClientAuthenticated
Notify subscribers on the client when the client is authenticated
virtual void OnStartClient()
Called when client starts, used to register message handlers if needed.
virtual void ConfigureHeadlessFrameRate()
Set the frame rate for a headless builds. Override to disable or modify.
string networkAddress
Server's address for clients to connect to.
virtual void OnStartClient()
This is invoked when the client is started.
bool runInBackground
Multiplayer games should always run in the background so the network doesn't time out.

◆ StartClient() [2/2]

void Mirror.NetworkManager.StartClient ( Uri  uri)

Starts the client, connects it to the server via Uri

Definition at line 350 of file NetworkManager.cs.

351 {
352 if (NetworkClient.active)
353 {
354 Debug.LogWarning("Client already started.");
355 return;
356 }
357
358 mode = NetworkManagerMode.ClientOnly;
359
360 InitializeSingleton();
361
362 if (runInBackground)
363 Application.runInBackground = true;
364
365 if (authenticator != null)
366 {
367 authenticator.OnStartClient();
368 authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated);
369 }
370
371 RegisterClientMessages();
372
373 // Debug.Log($"NetworkManager StartClient address:{uri}");
374 networkAddress = uri.Host;
375
376 NetworkClient.Connect(uri);
377
379 }

◆ StartHost()

void Mirror.NetworkManager.StartHost ( )

Starts a network "host" - a server and client in the same application.

Definition at line 382 of file NetworkManager.cs.

383 {
384 if (NetworkServer.active || NetworkClient.active)
385 {
386 Debug.LogWarning("Server or Client already started.");
387 return;
388 }
389
390 mode = NetworkManagerMode.Host;
391
392 // StartHost is inherently ASYNCHRONOUS (=doesn't finish immediately)
393 //
394 // Here is what it does:
395 // Listen
396 // ConnectHost
397 // if onlineScene:
398 // LoadSceneAsync
399 // ...
400 // FinishLoadSceneHost
401 // FinishStartHost
402 // SpawnObjects
403 // StartHostClient <= not guaranteed to happen after SpawnObjects if onlineScene is set!
404 // ClientAuth
405 // success: server sends changescene msg to client
406 // else:
407 // FinishStartHost
408 //
409 // there is NO WAY to make it synchronous because both LoadSceneAsync
410 // and LoadScene do not finish loading immediately. as long as we
411 // have the onlineScene feature, it will be asynchronous!
412
413 // setup server first
414 SetupServer();
415
416 // call OnStartHost AFTER SetupServer. this way we can use
417 // NetworkServer.Spawn etc. in there too. just like OnStartServer
418 // is called after the server is actually properly started.
419 OnStartHost();
420
421 // scene change needed? then change scene and spawn afterwards.
422 // => BEFORE host client connects. if client auth succeeds then the
423 // server tells it to load 'onlineScene'. we can't do that if
424 // server is still in 'offlineScene'. so load on server first.
425 if (IsServerOnlineSceneChangeNeeded())
426 {
427 // call FinishStartHost after changing scene.
428 finishStartHostPending = true;
430 }
431 // otherwise call FinishStartHost directly
432 else
433 {
434 FinishStartHost();
435 }
436 }
virtual void OnStartHost()
This is invoked when a host is started.
string onlineScene
Automatically switch to this scene upon going online (after connect/startserver).
virtual void ServerChangeScene(string newSceneName)
Change the server scene and all client's scenes across the network.

◆ StartServer()

void Mirror.NetworkManager.StartServer ( )

Starts the server, listening for incoming connections.

Definition at line 270 of file NetworkManager.cs.

271 {
272 if (NetworkServer.active)
273 {
274 Debug.LogWarning("Server already started.");
275 return;
276 }
277
278 mode = NetworkManagerMode.ServerOnly;
279
280 // StartServer is inherently ASYNCHRONOUS (=doesn't finish immediately)
281 //
282 // Here is what it does:
283 // Listen
284 // if onlineScene:
285 // LoadSceneAsync
286 // ...
287 // FinishLoadSceneServerOnly
288 // SpawnObjects
289 // else:
290 // SpawnObjects
291 //
292 // there is NO WAY to make it synchronous because both LoadSceneAsync
293 // and LoadScene do not finish loading immediately. as long as we
294 // have the onlineScene feature, it will be asynchronous!
295
296 SetupServer();
297
298 // scene change needed? then change scene and spawn afterwards.
299 if (IsServerOnlineSceneChangeNeeded())
300 {
302 }
303 // otherwise spawn directly
304 else
305 {
306 NetworkServer.SpawnObjects();
307 }
308 }

◆ StopClient()

void Mirror.NetworkManager.StopClient ( )

Stops and disconnects the client.

Definition at line 568 of file NetworkManager.cs.

569 {
570 if (mode == NetworkManagerMode.Offline)
571 return;
572
573 if (authenticator != null)
574 {
575 authenticator.OnClientAuthenticated.RemoveListener(OnClientAuthenticated);
576 authenticator.OnStopClient();
577 }
578
579 // Get Network Manager out of DDOL before going to offline scene
580 // to avoid collision and let a fresh Network Manager be created.
581 // IMPORTANT: .gameObject can be null if StopClient is called from
582 // OnApplicationQuit or from tests!
583 if (gameObject != null
584 && gameObject.scene.name == "DontDestroyOnLoad"
585 && !string.IsNullOrWhiteSpace(offlineScene)
586 && SceneManager.GetActiveScene().path != offlineScene)
587 SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene());
588
589 OnStopClient();
590
591 //Debug.Log("NetworkManager StopClient");
592
593 // set offline mode BEFORE changing scene so that FinishStartScene
594 // doesn't think we need initialize anything.
595 // set offline mode BEFORE NetworkClient.Disconnect so StopClient
596 // only runs once.
597 mode = NetworkManagerMode.Offline;
598
599 // shutdown client
600 NetworkClient.Disconnect();
601 NetworkClient.Shutdown();
602
603 // If this is the host player, StopServer will already be changing scenes.
604 // Check loadingSceneAsync to ensure we don't double-invoke the scene change.
605 // Check if NetworkServer.active because we can get here via Disconnect before server has started to change scenes.
606 if (!string.IsNullOrWhiteSpace(offlineScene) && !IsSceneActive(offlineScene) && loadingSceneAsync == null && !NetworkServer.active)
607 {
608 ClientChangeScene(offlineScene, SceneOperation.Normal);
609 }
610
611 networkSceneName = "";
612 }
virtual void OnStopClient()
Called when client stops, used to unregister message handlers if needed.
virtual void OnStopClient()
This is called when a client is stopped.

◆ StopHost()

void Mirror.NetworkManager.StopHost ( )

This stops both the client and the server that the manager is using.

Definition at line 510 of file NetworkManager.cs.

511 {
512 OnStopHost();
513
514 // calling OnTransportDisconnected was needed to fix
515 // https://github.com/vis2k/Mirror/issues/1515
516 // so that the host client receives a DisconnectMessage
517 // TODO reevaluate if this is still needed after all the disconnect
518 // fixes, and try to put this into LocalConnection.Disconnect!
519 NetworkServer.OnTransportDisconnected(NetworkConnection.LocalConnectionId);
520
521 StopClient();
522 StopServer();
523 }
virtual void OnStopHost()
This is called when a host is stopped.

◆ StopServer()

void Mirror.NetworkManager.StopServer ( )

Stops the server from listening and simulating the game.

Definition at line 526 of file NetworkManager.cs.

527 {
528 // return if already stopped to avoid recursion deadlock
529 if (!NetworkServer.active)
530 return;
531
532 if (authenticator != null)
533 {
534 authenticator.OnServerAuthenticated.RemoveListener(OnServerAuthenticated);
535 authenticator.OnStopServer();
536 }
537
538 // Get Network Manager out of DDOL before going to offline scene
539 // to avoid collision and let a fresh Network Manager be created.
540 // IMPORTANT: .gameObject can be null if StopClient is called from
541 // OnApplicationQuit or from tests!
542 if (gameObject != null
543 && gameObject.scene.name == "DontDestroyOnLoad"
544 && !string.IsNullOrWhiteSpace(offlineScene)
545 && SceneManager.GetActiveScene().path != offlineScene)
546 SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene());
547
548 OnStopServer();
549
550 //Debug.Log("NetworkManager StopServer");
551 NetworkServer.Shutdown();
552
553 // set offline mode BEFORE changing scene so that FinishStartScene
554 // doesn't think we need initialize anything.
555 mode = NetworkManagerMode.Offline;
556
557 if (!string.IsNullOrWhiteSpace(offlineScene))
558 {
560 }
561
562 startPositionIndex = 0;
563
564 networkSceneName = "";
565 }
UnityEventNetworkConnection OnServerAuthenticated
Notify subscribers on the server when a client is authenticated
virtual void OnStopServer()
Called when server stops, used to unregister message handlers if needed.
virtual void OnStopServer()
This is called when a server is stopped - including when a host is stopped.

◆ UnRegisterStartPosition()

static void Mirror.NetworkManager.UnRegisterStartPosition ( Transform  start)
static

Unregister a Transform from start positions.

Definition at line 1049 of file NetworkManager.cs.

1050 {
1051 //Debug.Log($"UnRegisterStartPosition: {start.name} {start.position}");
1052 startPositions.Remove(start);
1053 }

Member Data Documentation

◆ authenticator

NetworkAuthenticator Mirror.NetworkManager.authenticator

Definition at line 71 of file NetworkManager.cs.

◆ autoCreatePlayer

bool Mirror.NetworkManager.autoCreatePlayer = true

Enable to automatically create player objects on connect and on scene change.

Definition at line 84 of file NetworkManager.cs.

◆ autoStartServerBuild

bool Mirror.NetworkManager.autoStartServerBuild = true

Should the server auto-start when 'Server Build' is checked in build settings

Definition at line 34 of file NetworkManager.cs.

◆ clientLoadedScene

bool Mirror.NetworkManager.clientLoadedScene
protected

True if the client loaded a new scene when connecting to the server.

Definition at line 115 of file NetworkManager.cs.

◆ dontDestroyOnLoad

bool Mirror.NetworkManager.dontDestroyOnLoad = true

Enable to keep NetworkManager alive when changing scenes.

Definition at line 24 of file NetworkManager.cs.

◆ loadingSceneAsync

AsyncOperation Mirror.NetworkManager.loadingSceneAsync
static

Definition at line 745 of file NetworkManager.cs.

◆ maxConnections

int Mirror.NetworkManager.maxConnections = 100

The maximum number of concurrent network connections to support.

Definition at line 67 of file NetworkManager.cs.

◆ networkAddress

string Mirror.NetworkManager.networkAddress = "localhost"

Server's address for clients to connect to.

Definition at line 62 of file NetworkManager.cs.

◆ offlineScene

string Mirror.NetworkManager.offlineScene = ""

Automatically switch to this scene upon going offline (on start / on disconnect / on shutdown).

Definition at line 45 of file NetworkManager.cs.

◆ onlineScene

string Mirror.NetworkManager.onlineScene = ""

Automatically switch to this scene upon going online (after connect/startserver).

Definition at line 51 of file NetworkManager.cs.

◆ playerPrefab

GameObject Mirror.NetworkManager.playerPrefab

The default prefab to be used to create player objects on the server.

Definition at line 79 of file NetworkManager.cs.

◆ playerSpawnMethod

PlayerSpawnMethod Mirror.NetworkManager.playerSpawnMethod

Where to spawn players.

Definition at line 89 of file NetworkManager.cs.

◆ runInBackground

bool Mirror.NetworkManager.runInBackground = true

Multiplayer games should always run in the background so the network doesn't time out.

Definition at line 29 of file NetworkManager.cs.

◆ serverTickRate

int Mirror.NetworkManager.serverTickRate = 30

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.

Definition at line 38 of file NetworkManager.cs.

◆ spawnPrefabs

List<GameObject> Mirror.NetworkManager.spawnPrefabs = new List<GameObject>()

Prefabs that can be spawned over the network need to be registered here.

Definition at line 93 of file NetworkManager.cs.

◆ startPositionIndex

int Mirror.NetworkManager.startPositionIndex
static

Definition at line 97 of file NetworkManager.cs.

◆ startPositions

List<Transform> Mirror.NetworkManager.startPositions = new List<Transform>()
static

List of transforms populated by NetworkStartPositions

Definition at line 96 of file NetworkManager.cs.

◆ transport

Transport Mirror.NetworkManager.transport
protected

Definition at line 57 of file NetworkManager.cs.

Property Documentation

◆ isNetworkActive

bool Mirror.NetworkManager.isNetworkActive
get

True if the server is running or client is connected/connecting.

Definition at line 106 of file NetworkManager.cs.

◆ mode

NetworkManagerMode Mirror.NetworkManager.mode
get

Definition at line 123 of file NetworkManager.cs.

123{ get; private set; }

◆ networkSceneName

string Mirror.NetworkManager.networkSceneName = ""
staticgetprotected set

The name of the current network scene.

Definition at line 743 of file NetworkManager.cs.

743{ get; protected set; } = "";

◆ numPlayers

int Mirror.NetworkManager.numPlayers
get

Number of active player objects across all connections on the server.

Definition at line 103 of file NetworkManager.cs.

◆ singleton

NetworkManager Mirror.NetworkManager.singleton
staticgetset

The one and only NetworkManager

Definition at line 100 of file NetworkManager.cs.

100{ get; internal set; }