Mirror Networking
Mirror.NetworkServer Class Reference

NetworkServer handles remote connections and has a local connection for a local client. More...

Static Public Member Functions

static void ActivateHostScene ()
 
static void Listen (int maxConns)
 Starts server and listens to incoming connections with max connections limit. More...
 
static void Shutdown ()
 Shuts down the server and disconnects all clients More...
 
static bool AddConnection (NetworkConnectionToClient conn)
 Add a connection and setup callbacks. Returns true if not added yet. More...
 
static bool RemoveConnection (int connectionId)
 Removes a connection by connectionId. Returns true if removed.
 
static bool HasExternalConnections ()
 True if we have external connections (that are not host) More...
 
static void SendToAll< T > (T message, int channelId=Channels.Reliable, bool sendToReadyOnly=false)
 Send a message to all clients, even those that haven't joined the world yet (non ready) More...
 
static void SendToReady< T > (T message, int channelId=Channels.Reliable)
 Send a message to all clients which have joined the world (are ready). More...
 
static void SendToReadyObservers< T > (NetworkIdentity identity, T message, bool includeOwner=true, int channelId=Channels.Reliable)
 Send a message to only clients which are ready with option to include the owner of the object identity More...
 
static void SendToReadyObservers< T > (NetworkIdentity identity, T message, int channelId)
 Send a message to only clients which are ready including the owner of the NetworkIdentity More...
 
static void RegisterHandler< T > (Action< NetworkConnectionToClient, T > handler, bool requireAuthentication=true)
 Register a handler for message type T. Most should require authentication. More...
 
static void RegisterHandler< T > (Action< NetworkConnectionToClient, T, int > handler, bool requireAuthentication=true)
 Register a handler for message type T. Most should require authentication. More...
 
static void ReplaceHandler< T > (Action< NetworkConnectionToClient, T > handler, bool requireAuthentication=true)
 Replace a handler for message type T. Most should require authentication. More...
 
static void ReplaceHandler< T > (Action< T > handler, bool requireAuthentication=true)
 Replace a handler for message type T. Most should require authentication. More...
 
static void UnregisterHandler< T > ()
 Unregister a handler for a message type T. More...
 
static void ClearHandlers ()
 Clears all registered message handlers.
 
static void DisconnectAll ()
 Disconnect all connections, including the local connection. More...
 
static bool AddPlayerForConnection (NetworkConnectionToClient conn, GameObject player)
 Called by server after AddPlayer message to add the player for the connection. More...
 
static bool AddPlayerForConnection (NetworkConnectionToClient conn, GameObject player, Guid assetId)
 Called by server after AddPlayer message to add the player for the connection. More...
 
static bool ReplacePlayerForConnection (NetworkConnectionToClient conn, GameObject player, bool keepAuthority=false)
 Replaces connection's player object. The old object is not destroyed. More...
 
static bool ReplacePlayerForConnection (NetworkConnectionToClient conn, GameObject player, Guid assetId, bool keepAuthority=false)
 Replaces connection's player object. The old object is not destroyed. More...
 
static void SetClientReady (NetworkConnectionToClient conn)
 Flags client connection as ready (=joined world). More...
 
static void SetClientNotReady (NetworkConnectionToClient conn)
 Marks the client of the connection to be not-ready. More...
 
static void SetAllClientsNotReady ()
 Marks all connected clients as no longer ready. More...
 
static void RemovePlayerForConnection (NetworkConnection conn, bool destroyServerObject)
 Removes the player object from the connection More...
 
static void Spawn (GameObject obj, NetworkConnection ownerConnection=null)
 Spawn the given game object on all clients which are ready. More...
 
static void Spawn (GameObject obj, GameObject ownerPlayer)
 Spawns an object and also assigns Client Authority to the specified client. More...
 
static void Spawn (GameObject obj, Guid assetId, NetworkConnection ownerConnection=null)
 Spawns an object and also assigns Client Authority to the specified client. More...
 
static bool SpawnObjects ()
 Spawns NetworkIdentities in the scene on the server. More...
 
static void UnSpawn (GameObject obj)
 This takes an object that has been spawned and un-spawns it.
 
static void DestroyPlayerForConnection (NetworkConnectionToClient conn)
 Destroys all of the connection's owned objects on the server. More...
 
static void Destroy (GameObject obj)
 Destroys this object and corresponding objects on all clients.
 
static void RebuildObservers (NetworkIdentity identity, bool initialize)
 

Static Public Attributes

static int maxConnections
 
static Dictionary< int, NetworkConnectionToClientconnections
 Dictionary of all server connections, with connectionId as key More...
 
static readonly Dictionary< uint, NetworkIdentityspawned
 All spawned NetworkIdentities by netId. More...
 
static bool dontListen
 Single player mode can use dontListen to not accept incoming connections More...
 
static bool isLoadingScene
 
static InterestManagement aoi
 
static Action< NetworkConnectionToClientOnConnectedEvent
 
static Action< NetworkConnectionToClientOnDisconnectedEvent
 
static Action< NetworkConnectionToClient, TransportError, string > OnErrorEvent
 

Properties

static NetworkConnectionToClient localConnection [get]
 Connection to host mode client (if any) More...
 
static bool localClientActive [get]
 True is a local client is currently active on the server More...
 
static bool active [get, set]
 active checks if the server has been started More...
 

Detailed Description

NetworkServer handles remote connections and has a local connection for a local client.

Definition at line 10 of file NetworkServer.cs.

Member Function Documentation

◆ ActivateHostScene()

static void Mirror.NetworkServer.ActivateHostScene ( )
static

Definition at line 101 of file NetworkServer.cs.

102 {
103 foreach (NetworkIdentity identity in spawned.Values)
104 {
105 if (!identity.isClient)
106 {
107 // Debug.Log($"ActivateHostScene {identity.netId} {identity}");
108 identity.OnStartClient();
109 }
110 }
111 }
static readonly Dictionary< uint, NetworkIdentity > spawned
All spawned NetworkIdentities by netId.

◆ AddConnection()

static bool Mirror.NetworkServer.AddConnection ( NetworkConnectionToClient  conn)
static

Add a connection and setup callbacks. Returns true if not added yet.

Definition at line 226 of file NetworkServer.cs.

227 {
228 if (!connections.ContainsKey(conn.connectionId))
229 {
230 // connection cannot be null here or conn.connectionId
231 // would throw NRE
232 connections[conn.connectionId] = conn;
233 return true;
234 }
235 // already a connection with this id
236 return false;
237 }
static Dictionary< int, NetworkConnectionToClient > connections
Dictionary of all server connections, with connectionId as key

◆ AddPlayerForConnection() [1/2]

static bool Mirror.NetworkServer.AddPlayerForConnection ( NetworkConnectionToClient  conn,
GameObject  player 
)
static

Called by server after AddPlayer message to add the player for the connection.

Definition at line 716 of file NetworkServer.cs.

717 {
718 NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
719 if (identity == null)
720 {
721 Debug.LogWarning($"AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
722 return false;
723 }
724
725 // cannot have a player object in "Add" version
726 if (conn.identity != null)
727 {
728 Debug.Log("AddPlayer: player object already exists");
729 return false;
730 }
731
732 // make sure we have a controller before we call SetClientReady
733 // because the observers will be rebuilt only if we have a controller
734 conn.identity = identity;
735
736 // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
737 identity.SetClientOwner(conn);
738
739 // special case, we are in host mode, set hasAuthority to true so that all overrides see it
740 if (conn is LocalConnectionToClient)
741 {
742 identity.hasAuthority = true;
743 NetworkClient.InternalAddPlayer(identity);
744 }
745
746 // set ready if not set yet
747 SetClientReady(conn);
748
749 // Debug.Log($"Adding new playerGameObject object netId: {identity.netId} asset ID: {identity.assetId}");
750
751 Respawn(identity);
752 return true;
753 }
static void SetClientReady(NetworkConnectionToClient conn)
Flags client connection as ready (=joined world).

◆ AddPlayerForConnection() [2/2]

static bool Mirror.NetworkServer.AddPlayerForConnection ( NetworkConnectionToClient  conn,
GameObject  player,
Guid  assetId 
)
static

Called by server after AddPlayer message to add the player for the connection.

Definition at line 762 of file NetworkServer.cs.

763 {
764 if (GetNetworkIdentity(player, out NetworkIdentity identity))
765 {
766 identity.assetId = assetId;
767 }
768 return AddPlayerForConnection(conn, player);
769 }
static bool AddPlayerForConnection(NetworkConnectionToClient conn, GameObject player)
Called by server after AddPlayer message to add the player for the connection.

◆ DestroyPlayerForConnection()

static void Mirror.NetworkServer.DestroyPlayerForConnection ( NetworkConnectionToClient  conn)
static

Destroys all of the connection's owned objects on the server.

Definition at line 1290 of file NetworkServer.cs.

1291 {
1292 // destroy all objects owned by this connection, including the player object
1293 conn.DestroyOwnedObjects();
1294 // remove connection from all of its observing entities observers
1295 // fixes https://github.com/vis2k/Mirror/issues/2737
1296 // -> cleaning those up in NetworkConnection.Disconnect is NOT enough
1297 // because voluntary disconnects from the other end don't call
1298 // NetworkConnectionn.Disconnect()
1299 conn.RemoveFromObservingsObservers();
1300 conn.identity = null;
1301 }

◆ DisconnectAll()

static void Mirror.NetworkServer.DisconnectAll ( )
static

Disconnect all connections, including the local connection.

Definition at line 672 of file NetworkServer.cs.

673 {
674 // disconnect and remove all connections.
675 // we can not use foreach here because if
676 // conn.Disconnect -> Transport.ServerDisconnect calls
677 // OnDisconnect -> NetworkServer.OnDisconnect(connectionId)
678 // immediately then OnDisconnect would remove the connection while
679 // we are iterating here.
680 // see also: https://github.com/vis2k/Mirror/issues/2357
681 // this whole process should be simplified some day.
682 // until then, let's copy .Values to avoid InvalidOperatinException.
683 // note that this is only called when stopping the server, so the
684 // copy is no performance problem.
685 foreach (NetworkConnectionToClient conn in connections.Values.ToList())
686 {
687 // disconnect via connection->transport
688 conn.Disconnect();
689
690 // we want this function to be synchronous: handle disconnect
691 // events and clean up fully before returning.
692 // -> OnTransportDisconnected can safely be called without
693 // waiting for the Transport's callback.
694 // -> it has checks to only run once.
695
696 // call OnDisconnected unless local player in host mod
697 // TODO unnecessary check?
698 if (conn.connectionId != NetworkConnection.LocalConnectionId)
699 OnTransportDisconnected(conn.connectionId);
700 }
701
702 // cleanup
703 connections.Clear();
704 localConnection = null;
705 active = false;
706 }
static NetworkConnectionToClient localConnection
Connection to host mode client (if any)
static bool active
active checks if the server has been started

◆ HasExternalConnections()

static bool Mirror.NetworkServer.HasExternalConnections ( )
static

True if we have external connections (that are not host)

Definition at line 268 of file NetworkServer.cs.

269 {
270 // any connections?
271 if (connections.Count > 0)
272 {
273 // only host connection?
274 if (connections.Count == 1 && localConnection != null)
275 return false;
276
277 // otherwise we have real external connections
278 return true;
279 }
280 return false;
281 }

◆ Listen()

static void Mirror.NetworkServer.Listen ( int  maxConns)
static

Starts server and listens to incoming connections with max connections limit.

Definition at line 121 of file NetworkServer.cs.

122 {
123 Initialize();
124 maxConnections = maxConns;
125
126 // only start server if we want to listen
127 if (!dontListen)
128 {
129 Transport.activeTransport.ServerStart();
130 //Debug.Log("Server started listening");
131 }
132
133 active = true;
134 RegisterMessageHandlers();
135 }
static bool dontListen
Single player mode can use dontListen to not accept incoming connections

◆ RebuildObservers()

static void Mirror.NetworkServer.RebuildObservers ( NetworkIdentity  identity,
bool  initialize 
)
static

Definition at line 1554 of file NetworkServer.cs.

1555 {
1556 // observers are null until OnStartServer creates them
1557 if (identity.observers == null)
1558 return;
1559
1560 // if there is no interest management system,
1561 // or if 'force shown' then add all connections
1562 if (aoi == null || identity.visible == Visibility.ForceShown)
1563 {
1564 RebuildObserversDefault(identity, initialize);
1565 }
1566 // otherwise let interest management system rebuild
1567 else
1568 {
1569 RebuildObserversCustom(identity, initialize);
1570 }
1571 }

◆ RegisterHandler< T >() [1/2]

static void Mirror.NetworkServer.RegisterHandler< T > ( Action< NetworkConnectionToClient, T >  handler,
bool  requireAuthentication = true 
)
static

Register a handler for message type T. Most should require authentication.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 608 of file NetworkServer.cs.

609 : struct, NetworkMessage
610 {
611 ushort msgType = MessagePacking.GetId<T>();
612 if (handlers.ContainsKey(msgType))
613 {
614 Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
615 }
616 handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
617 }

◆ RegisterHandler< T >() [2/2]

static void Mirror.NetworkServer.RegisterHandler< T > ( Action< NetworkConnectionToClient, T, int >  handler,
bool  requireAuthentication = true 
)
static

Register a handler for message type T. Most should require authentication.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 621 of file NetworkServer.cs.

622 : struct, NetworkMessage
623 {
624 ushort msgType = MessagePacking.GetId<T>();
625 if (handlers.ContainsKey(msgType))
626 {
627 Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
628 }
629 handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
630 }

◆ RemovePlayerForConnection()

static void Mirror.NetworkServer.RemovePlayerForConnection ( NetworkConnection  conn,
bool  destroyServerObject 
)
static

Removes the player object from the connection

Definition at line 912 of file NetworkServer.cs.

913 {
914 if (conn.identity != null)
915 {
916 if (destroyServerObject)
917 Destroy(conn.identity.gameObject);
918 else
919 UnSpawn(conn.identity.gameObject);
920
921 conn.identity = null;
922 }
923 //else Debug.Log($"Connection {conn} has no identity");
924 }
static void UnSpawn(GameObject obj)
This takes an object that has been spawned and un-spawns it.
static void Destroy(GameObject obj)
Destroys this object and corresponding objects on all clients.

◆ ReplaceHandler< T >() [1/2]

static void Mirror.NetworkServer.ReplaceHandler< T > ( Action< NetworkConnectionToClient, T >  handler,
bool  requireAuthentication = true 
)
static

Replace a handler for message type T. Most should require authentication.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 633 of file NetworkServer.cs.

634 : struct, NetworkMessage
635 {
636 ushort msgType = MessagePacking.GetId<T>();
637 handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
638 }

◆ ReplaceHandler< T >() [2/2]

static void Mirror.NetworkServer.ReplaceHandler< T > ( Action< T >  handler,
bool  requireAuthentication = true 
)
static

Replace a handler for message type T. Most should require authentication.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 641 of file NetworkServer.cs.

642 : struct, NetworkMessage
643 {
644 ReplaceHandler<T>((_, value) => { handler(value); }, requireAuthentication);
645 }
static void ReplaceHandler< T >(Action< NetworkConnectionToClient, T > handler, bool requireAuthentication=true)
Replace a handler for message type T. Most should require authentication.

◆ ReplacePlayerForConnection() [1/2]

static bool Mirror.NetworkServer.ReplacePlayerForConnection ( NetworkConnectionToClient  conn,
GameObject  player,
bool  keepAuthority = false 
)
static

Replaces connection's player object. The old object is not destroyed.

Definition at line 774 of file NetworkServer.cs.

775 {
776 NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
777 if (identity == null)
778 {
779 Debug.LogError($"ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
780 return false;
781 }
782
783 if (identity.connectionToClient != null && identity.connectionToClient != conn)
784 {
785 Debug.LogError($"Cannot replace player for connection. New player is already owned by a different connection{player}");
786 return false;
787 }
788
789 //NOTE: there can be an existing player
790 //Debug.Log("NetworkServer ReplacePlayer");
791
792 NetworkIdentity previousPlayer = conn.identity;
793
794 conn.identity = identity;
795
796 // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
797 identity.SetClientOwner(conn);
798
799 // special case, we are in host mode, set hasAuthority to true so that all overrides see it
800 if (conn is LocalConnectionToClient)
801 {
802 identity.hasAuthority = true;
803 NetworkClient.InternalAddPlayer(identity);
804 }
805
806 // add connection to observers AFTER the playerController was set.
807 // by definition, there is nothing to observe if there is no player
808 // controller.
809 //
810 // IMPORTANT: do this in AddPlayerForConnection & ReplacePlayerForConnection!
811 SpawnObserversForConnection(conn);
812
813 //Debug.Log($"Replacing playerGameObject object netId:{player.GetComponent<NetworkIdentity>().netId} asset ID {player.GetComponent<NetworkIdentity>().assetId}");
814
815 Respawn(identity);
816
817 if (keepAuthority)
818 {
819 // This needs to be sent to clear isLocalPlayer on
820 // client while keeping hasAuthority true
821 SendChangeOwnerMessage(previousPlayer, conn);
822 }
823 else
824 {
825 // This clears both isLocalPlayer and hasAuthority on client
826 previousPlayer.RemoveClientAuthority();
827 }
828
829 return true;
830 }

◆ ReplacePlayerForConnection() [2/2]

static bool Mirror.NetworkServer.ReplacePlayerForConnection ( NetworkConnectionToClient  conn,
GameObject  player,
Guid  assetId,
bool  keepAuthority = false 
)
static

Replaces connection's player object. The old object is not destroyed.

Definition at line 835 of file NetworkServer.cs.

836 {
837 if (GetNetworkIdentity(player, out NetworkIdentity identity))
838 {
839 identity.assetId = assetId;
840 }
841 return ReplacePlayerForConnection(conn, player, keepAuthority);
842 }
static bool ReplacePlayerForConnection(NetworkConnectionToClient conn, GameObject player, bool keepAuthority=false)
Replaces connection's player object. The old object is not destroyed.

◆ SendToAll< T >()

static void Mirror.NetworkServer.SendToAll< T > ( message,
int  channelId = Channels.Reliable,
bool  sendToReadyOnly = false 
)
static

Send a message to all clients, even those that haven't joined the world yet (non ready)

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 285 of file NetworkServer.cs.

286 : struct, NetworkMessage
287 {
288 if (!active)
289 {
290 Debug.LogWarning("Can not send using NetworkServer.SendToAll<T>(T msg) because NetworkServer is not active");
291 return;
292 }
293
294 // Debug.Log($"Server.SendToAll {typeof(T)}");
295 using (NetworkWriterPooled writer = NetworkWriterPool.Get())
296 {
297 // pack message only once
298 MessagePacking.Pack(message, writer);
299 ArraySegment<byte> segment = writer.ToArraySegment();
300
301 // filter and then send to all internet connections at once
302 // -> makes code more complicated, but is HIGHLY worth it to
303 // avoid allocations, allow for multicast, etc.
304 int count = 0;
305 foreach (NetworkConnectionToClient conn in connections.Values)
306 {
307 if (sendToReadyOnly && !conn.isReady)
308 continue;
309
310 count++;
311 conn.Send(segment, channelId);
312 }
313
314 NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
315 }
316 }

◆ SendToReady< T >()

static void Mirror.NetworkServer.SendToReady< T > ( message,
int  channelId = Channels.Reliable 
)
static

Send a message to all clients which have joined the world (are ready).

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 320 of file NetworkServer.cs.

321 : struct, NetworkMessage
322 {
323 if (!active)
324 {
325 Debug.LogWarning("Can not send using NetworkServer.SendToReady<T>(T msg) because NetworkServer is not active");
326 return;
327 }
328
329 SendToAll(message, channelId, true);
330 }

◆ SendToReadyObservers< T >() [1/2]

static void Mirror.NetworkServer.SendToReadyObservers< T > ( NetworkIdentity  identity,
message,
bool  includeOwner = true,
int  channelId = Channels.Reliable 
)
static

Send a message to only clients which are ready with option to include the owner of the object identity

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 358 of file NetworkServer.cs.

359 : struct, NetworkMessage
360 {
361 // Debug.Log($"Server.SendToReady {typeof(T)}");
362 if (identity == null || identity.observers == null || identity.observers.Count == 0)
363 return;
364
365 using (NetworkWriterPooled writer = NetworkWriterPool.Get())
366 {
367 // pack message only once
368 MessagePacking.Pack(message, writer);
369 ArraySegment<byte> segment = writer.ToArraySegment();
370
371 int count = 0;
372 foreach (NetworkConnection conn in identity.observers.Values)
373 {
374 bool isOwner = conn == identity.connectionToClient;
375 if ((!isOwner || includeOwner) && conn.isReady)
376 {
377 count++;
378 conn.Send(segment, channelId);
379 }
380 }
381
382 NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
383 }
384 }

◆ SendToReadyObservers< T >() [2/2]

static void Mirror.NetworkServer.SendToReadyObservers< T > ( NetworkIdentity  identity,
message,
int  channelId 
)
static

Send a message to only clients which are ready including the owner of the NetworkIdentity

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 388 of file NetworkServer.cs.

389 : struct, NetworkMessage
390 {
391 SendToReadyObservers(identity, message, true, channelId);
392 }

◆ SetAllClientsNotReady()

static void Mirror.NetworkServer.SetAllClientsNotReady ( )
static

Marks all connected clients as no longer ready.

Definition at line 879 of file NetworkServer.cs.

880 {
881 foreach (NetworkConnectionToClient conn in connections.Values)
882 {
883 SetClientNotReady(conn);
884 }
885 }
static void SetClientNotReady(NetworkConnectionToClient conn)
Marks the client of the connection to be not-ready.

◆ SetClientNotReady()

static void Mirror.NetworkServer.SetClientNotReady ( NetworkConnectionToClient  conn)
static

Marks the client of the connection to be not-ready.

Definition at line 868 of file NetworkServer.cs.

869 {
870 conn.isReady = false;
871 conn.RemoveFromObservingsObservers();
872 conn.Send(new NotReadyMessage());
873 }

◆ SetClientReady()

static void Mirror.NetworkServer.SetClientReady ( NetworkConnectionToClient  conn)
static

Flags client connection as ready (=joined world).

Definition at line 852 of file NetworkServer.cs.

853 {
854 // Debug.Log($"SetClientReadyInternal for conn:{conn}");
855
856 // set ready
857 conn.isReady = true;
858
859 // client is ready to start spawning objects
860 if (conn.identity != null)
861 SpawnObserversForConnection(conn);
862 }

◆ Shutdown()

static void Mirror.NetworkServer.Shutdown ( )
static

Shuts down the server and disconnects all clients

Definition at line 171 of file NetworkServer.cs.

172 {
173 if (initialized)
174 {
176
177 // stop the server.
178 // we do NOT call Transport.Shutdown, because someone only
179 // called NetworkServer.Shutdown. we can't assume that the
180 // client is supposed to be shut down too!
181 //
182 // NOTE: stop no matter what, even if 'dontListen':
183 // someone might enabled dontListen at runtime.
184 // but we still need to stop the server.
185 // fixes https://github.com/vis2k/Mirror/issues/2536
186 Transport.activeTransport.ServerStop();
187
188 // transport handlers are hooked into when initializing.
189 // so only remove them when shutting down.
190 RemoveTransportHandlers();
191
192 initialized = false;
193 }
194
195 // Reset all statics here....
196 dontListen = false;
197 active = false;
198 isLoadingScene = false;
199
200 localConnection = null;
201
202 connections.Clear();
203 connectionsCopy.Clear();
204 handlers.Clear();
205 newObservers.Clear();
206
207 // this calls spawned.Clear()
208 CleanupSpawned();
209
210 // sets nextNetworkId to 1
211 // sets clientAuthorityCallback to null
212 // sets previousLocalPlayer to null
213 NetworkIdentity.ResetStatics();
214
215 // clear events. someone might have hooked into them before, but
216 // we don't want to use those hooks after Shutdown anymore.
217 OnConnectedEvent = null;
218 OnDisconnectedEvent = null;
219 OnErrorEvent = null;
220
221 if (aoi != null) aoi.Reset();
222 }
static void DisconnectAll()
Disconnect all connections, including the local connection.

◆ Spawn() [1/3]

static void Mirror.NetworkServer.Spawn ( GameObject  obj,
GameObject  ownerPlayer 
)
static

Spawns an object and also assigns Client Authority to the specified client.

Definition at line 1107 of file NetworkServer.cs.

1108 {
1109 NetworkIdentity identity = ownerPlayer.GetComponent<NetworkIdentity>();
1110 if (identity == null)
1111 {
1112 Debug.LogError("Player object has no NetworkIdentity");
1113 return;
1114 }
1115
1116 if (identity.connectionToClient == null)
1117 {
1118 Debug.LogError("Player object is not a player.");
1119 return;
1120 }
1121
1122 Spawn(obj, identity.connectionToClient);
1123 }
static void Spawn(GameObject obj, NetworkConnection ownerConnection=null)
Spawn the given game object on all clients which are ready.

◆ Spawn() [2/3]

static void Mirror.NetworkServer.Spawn ( GameObject  obj,
Guid  assetId,
NetworkConnection  ownerConnection = null 
)
static

Spawns an object and also assigns Client Authority to the specified client.

Definition at line 1127 of file NetworkServer.cs.

1128 {
1129 if (GetNetworkIdentity(obj, out NetworkIdentity identity))
1130 {
1131 identity.assetId = assetId;
1132 }
1133 SpawnObject(obj, ownerConnection);
1134 }

◆ Spawn() [3/3]

static void Mirror.NetworkServer.Spawn ( GameObject  obj,
NetworkConnection  ownerConnection = null 
)
static

Spawn the given game object on all clients which are ready.

Definition at line 1100 of file NetworkServer.cs.

1101 {
1102 SpawnObject(obj, ownerConnection);
1103 }

◆ SpawnObjects()

static bool Mirror.NetworkServer.SpawnObjects ( )
static

Spawns NetworkIdentities in the scene on the server.

Definition at line 1155 of file NetworkServer.cs.

1156 {
1157 // only if server active
1158 if (!active)
1159 return false;
1160
1161 NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll<NetworkIdentity>();
1162
1163 // first pass: activate all scene objects
1164 foreach (NetworkIdentity identity in identities)
1165 {
1166 if (ValidateSceneObject(identity))
1167 {
1168 // Debug.Log($"SpawnObjects sceneId:{identity.sceneId:X} name:{identity.gameObject.name}");
1169 identity.gameObject.SetActive(true);
1170
1171 // fix https://github.com/vis2k/Mirror/issues/2778:
1172 // -> SetActive(true) does NOT call Awake() if the parent
1173 // is inactive
1174 // -> we need Awake() to initialize NetworkBehaviours[] etc.
1175 // because our second pass below spawns and works with it
1176 // => detect this situation and manually call Awake for
1177 // proper initialization
1178 if (!identity.gameObject.activeInHierarchy)
1179 identity.Awake();
1180 }
1181 }
1182
1183 // second pass: spawn all scene objects
1184 foreach (NetworkIdentity identity in identities)
1185 {
1186 if (ValidateSceneObject(identity))
1187 // pass connection so that authority is not lost when server loads a scene
1188 // https://github.com/vis2k/Mirror/pull/2987
1189 Spawn(identity.gameObject, identity.connectionToClient);
1190 }
1191
1192 return true;
1193 }

◆ UnregisterHandler< T >()

static void Mirror.NetworkServer.UnregisterHandler< T > ( )
static

Unregister a handler for a message type T.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 648 of file NetworkServer.cs.

649 : struct, NetworkMessage
650 {
651 ushort msgType = MessagePacking.GetId<T>();
652 handlers.Remove(msgType);
653 }

Member Data Documentation

◆ aoi

InterestManagement Mirror.NetworkServer.aoi
static

Definition at line 46 of file NetworkServer.cs.

◆ connections

Dictionary<int, NetworkConnectionToClient> Mirror.NetworkServer.connections
static
Initial value:
=
new Dictionary<int, NetworkConnectionToClient>()

Dictionary of all server connections, with connectionId as key

Definition at line 22 of file NetworkServer.cs.

◆ dontListen

bool Mirror.NetworkServer.dontListen
static

Single player mode can use dontListen to not accept incoming connections

Definition at line 36 of file NetworkServer.cs.

◆ isLoadingScene

bool Mirror.NetworkServer.isLoadingScene
static

Definition at line 42 of file NetworkServer.cs.

◆ maxConnections

int Mirror.NetworkServer.maxConnections
static

Definition at line 13 of file NetworkServer.cs.

◆ OnConnectedEvent

Action<NetworkConnectionToClient> Mirror.NetworkServer.OnConnectedEvent
static

Definition at line 53 of file NetworkServer.cs.

◆ OnDisconnectedEvent

Action<NetworkConnectionToClient> Mirror.NetworkServer.OnDisconnectedEvent
static

Definition at line 54 of file NetworkServer.cs.

◆ OnErrorEvent

Action<NetworkConnectionToClient, TransportError, string> Mirror.NetworkServer.OnErrorEvent
static

Definition at line 55 of file NetworkServer.cs.

◆ spawned

readonly Dictionary<uint, NetworkIdentity> Mirror.NetworkServer.spawned
static
Initial value:
=
new Dictionary<uint, NetworkIdentity>()

All spawned NetworkIdentities by netId.

Definition at line 31 of file NetworkServer.cs.

Property Documentation

◆ active

bool Mirror.NetworkServer.active
staticgetset

active checks if the server has been started

Definition at line 39 of file NetworkServer.cs.

39{ get; internal set; }

◆ localClientActive

bool Mirror.NetworkServer.localClientActive
staticget

True is a local client is currently active on the server

Definition at line 19 of file NetworkServer.cs.

◆ localConnection

NetworkConnectionToClient Mirror.NetworkServer.localConnection
staticget

Connection to host mode client (if any)

Definition at line 16 of file NetworkServer.cs.

16{ get; private set; }