Mirror Networking
Mirror.NetworkClient Class Reference

NetworkClient with connection to server. More...

Static Public Member Functions

static void Connect (string address)
 Connect client to a NetworkServer by address. More...
 
static void Connect (Uri uri)
 Connect client to a NetworkServer by Uri. More...
 
static void ConnectHost ()
 
static void ConnectLocalServer ()
 Connect host mode More...
 
static void Disconnect ()
 Disconnect from server. More...
 
static void Send< T > (T message, int channelId=Channels.Reliable)
 Send a NetworkMessage to the server over the given channel. More...
 
static void RegisterHandler< T > (Action< T > handler, bool requireAuthentication=true)
 Register a handler for a message type T. Most should require authentication. More...
 
static void ReplaceHandler< T > (Action< NetworkConnection, T > handler, bool requireAuthentication=true)
 Replace a handler for a particular message type. Should require authentication by default. More...
 
static void ReplaceHandler< T > (Action< T > handler, bool requireAuthentication=true)
 Replace a handler for a particular message type. Should require authentication by default. More...
 
static bool UnregisterHandler< T > ()
 Unregister a message handler of type T. More...
 
static bool GetPrefab (Guid assetId, out GameObject prefab)
 Find the registered prefab for this asset id. More...
 
static void RegisterPrefab (GameObject prefab, Guid newAssetId)
 Register spawnable prefab with custom assetId. More...
 
static void RegisterPrefab (GameObject prefab)
 Register spawnable prefab. More...
 
static void RegisterPrefab (GameObject prefab, Guid newAssetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
 Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers. More...
 
static void RegisterPrefab (GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
 Register a spawnable prefab with custom spawn/unspawn handlers. More...
 
static void RegisterPrefab (GameObject prefab, Guid newAssetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
 Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers. More...
 
static void RegisterPrefab (GameObject prefab, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
 Register a spawnable prefab with custom spawn/unspawn handlers. More...
 
static void UnregisterPrefab (GameObject prefab)
 Removes a registered spawn prefab that was setup with NetworkClient.RegisterPrefab. More...
 
static void RegisterSpawnHandler (Guid assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
 This is an advanced spawning function that registers a custom assetId with the spawning system. More...
 
static void RegisterSpawnHandler (Guid assetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
 This is an advanced spawning function that registers a custom assetId with the spawning system. More...
 
static void UnregisterSpawnHandler (Guid assetId)
 Removes a registered spawn handler function that was registered with NetworkClient.RegisterHandler(). More...
 
static void ClearSpawners ()
 This clears the registered spawn prefabs and spawn handler functions for this client. More...
 
static bool Ready ()
 Sends Ready message to server, indicating that we loaded the scene, ready to enter the game. More...
 
static bool AddPlayer ()
 Sends AddPlayer message to the server, indicating that we want to join the world. More...
 
static void PrepareToSpawnSceneObjects ()
 Call this after loading/unloading a scene in the client after connection to register the spawnable objects More...
 
static void DestroyAllClientObjects ()
 Destroys all networked objects on the client. More...
 
static void Shutdown ()
 Shutdown the client. More...
 

Static Public Attributes

static readonly Dictionary< uint, NetworkIdentityspawned
 All spawned NetworkIdentities by netId. More...
 
static bool ready
 True if client is ready (= joined world). More...
 
static Action OnConnectedEvent
 
static Action OnDisconnectedEvent
 
static Action< TransportError, string > OnErrorEvent
 
static readonly Dictionary< Guid, GameObject > prefabs
 Registered spawnable prefabs by assetId. More...
 
static InterestManagement aoi
 
static bool isLoadingScene
 

Properties

static NetworkConnection connection [get, set]
 Client's NetworkConnection to server. More...
 
static NetworkIdentity localPlayer [get, set]
 NetworkIdentity of the localPlayer More...
 
static string serverIp [get]
 IP address of the connection to server. More...
 
static bool active [get]
 active is true while a client is connecting/connected More...
 
static bool isConnecting [get]
 Check if client is connecting (before connected). More...
 
static bool isConnected [get]
 Check if client is connected (after connecting). More...
 
static bool isHostClient [get]
 True if client is running in host mode. More...
 

Detailed Description

NetworkClient with connection to server.

Definition at line 21 of file NetworkClient.cs.

Member Function Documentation

◆ AddPlayer()

static bool Mirror.NetworkClient.AddPlayer ( )
static

Sends AddPlayer message to the server, indicating that we want to join the world.

Definition at line 974 of file NetworkClient.cs.

975 {
976 // ensure valid ready connection
977 if (connection == null)
978 {
979 Debug.LogError("AddPlayer requires a valid NetworkClient.connection.");
980 return false;
981 }
982
983 // UNET checked 'if readyConnection != null'.
984 // in other words, we need a connection and we need to be ready.
985 if (!ready)
986 {
987 Debug.LogError("AddPlayer requires a ready NetworkClient.");
988 return false;
989 }
990
991 if (connection.identity != null)
992 {
993 Debug.LogError("NetworkClient.AddPlayer: a PlayerController was already added. Did you call AddPlayer twice?");
994 return false;
995 }
996
997 // Debug.Log($"NetworkClient.AddPlayer() called with connection {readyConnection}");
998 connection.Send(new AddPlayerMessage());
999 return true;
1000 }
static bool ready
True if client is ready (= joined world).
static NetworkConnection connection
Client's NetworkConnection to server.
NetworkIdentity identity
This connection's main object (usually the player object).

◆ ClearSpawners()

static void Mirror.NetworkClient.ClearSpawners ( )
static

This clears the registered spawn prefabs and spawn handler functions for this client.

Definition at line 900 of file NetworkClient.cs.

901 {
902 prefabs.Clear();
903 spawnHandlers.Clear();
904 unspawnHandlers.Clear();
905 }
static readonly Dictionary< Guid, GameObject > prefabs
Registered spawnable prefabs by assetId.

◆ Connect() [1/2]

static void Mirror.NetworkClient.Connect ( string  address)
static

Connect client to a NetworkServer by address.

Definition at line 160 of file NetworkClient.cs.

161 {
162 // Debug.Log($"Client Connect: {address}");
163 Debug.Assert(Transport.activeTransport != null, "There was no active transport when calling NetworkClient.Connect, If you are calling Connect manually then make sure to set 'Transport.activeTransport' first");
164
165 RegisterSystemHandlers(false);
166 Transport.activeTransport.enabled = true;
167 AddTransportHandlers();
168
169 connectState = ConnectState.Connecting;
170 Transport.activeTransport.ClientConnect(address);
171
172 connection = new NetworkConnectionToServer();
173 }

◆ Connect() [2/2]

static void Mirror.NetworkClient.Connect ( Uri  uri)
static

Connect client to a NetworkServer by Uri.

Definition at line 176 of file NetworkClient.cs.

177 {
178 // Debug.Log($"Client Connect: {uri}");
179 Debug.Assert(Transport.activeTransport != null, "There was no active transport when calling NetworkClient.Connect, If you are calling Connect manually then make sure to set 'Transport.activeTransport' first");
180
181 RegisterSystemHandlers(false);
182 Transport.activeTransport.enabled = true;
183 AddTransportHandlers();
184
185 connectState = ConnectState.Connecting;
186 Transport.activeTransport.ClientConnect(uri);
187
188 connection = new NetworkConnectionToServer();
189 }

◆ ConnectHost()

static void Mirror.NetworkClient.ConnectHost ( )
static

Definition at line 193 of file NetworkClient.cs.

194 {
195 //Debug.Log("Client Connect Host to Server");
196
197 RegisterSystemHandlers(true);
198
199 connectState = ConnectState.Connected;
200
201 // create local connection objects and connect them
202 LocalConnectionToServer connectionToServer = new LocalConnectionToServer();
203 LocalConnectionToClient connectionToClient = new LocalConnectionToClient();
204 connectionToServer.connectionToClient = connectionToClient;
205 connectionToClient.connectionToServer = connectionToServer;
206
207 connection = connectionToServer;
208
209 // create server connection to local client
210 NetworkServer.SetLocalConnection(connectionToClient);
211 }

◆ ConnectLocalServer()

static void Mirror.NetworkClient.ConnectLocalServer ( )
static

Connect host mode

Definition at line 216 of file NetworkClient.cs.

217 {
218 // call server OnConnected with server's connection to client
219 NetworkServer.OnConnected(NetworkServer.localConnection);
220
221 // call client OnConnected with client's connection to server
222 // => previously we used to send a ConnectMessage to
223 // NetworkServer.localConnection. this would queue the message
224 // until NetworkClient.Update processes it.
225 // => invoking the client's OnConnected event directly here makes
226 // tests fail. so let's do it exactly the same order as before by
227 // queueing the event for next Update!
228 //OnConnectedEvent?.Invoke(connection);
229 ((LocalConnectionToServer)connection).QueueConnectedEvent();
230 }

◆ DestroyAllClientObjects()

static void Mirror.NetworkClient.DestroyAllClientObjects ( )
static

Destroys all networked objects on the client.

Definition at line 1444 of file NetworkClient.cs.

1445 {
1446 // user can modify spawned lists which causes InvalidOperationException
1447 // list can modified either in UnSpawnHandler or in OnDisable/OnDestroy
1448 // we need the Try/Catch so that the rest of the shutdown does not get stopped
1449 try
1450 {
1451 foreach (NetworkIdentity identity in spawned.Values)
1452 {
1453 if (identity != null && identity.gameObject != null)
1454 {
1455 if (identity.isLocalPlayer)
1456 identity.OnStopLocalPlayer();
1457
1458 identity.OnStopClient();
1459
1460 // NetworkClient.Shutdown calls DestroyAllClientObjects.
1461 // which destroys all objects in NetworkClient.spawned.
1462 // => NC.spawned contains owned & observed objects
1463 // => in host mode, we CAN NOT destroy observed objects.
1464 // => that would destroy them other connection's objects
1465 // on the host server, making them disconnect.
1466 // https://github.com/vis2k/Mirror/issues/2954
1467 bool hostOwned = identity.connectionToServer is LocalConnectionToServer;
1468 bool shouldDestroy = !identity.isServer || hostOwned;
1469 if (shouldDestroy)
1470 {
1471 bool wasUnspawned = InvokeUnSpawnHandler(identity.assetId, identity.gameObject);
1472
1473 // unspawned objects should be reset for reuse later.
1474 if (wasUnspawned)
1475 {
1476 identity.Reset();
1477 }
1478 // without unspawn handler, we need to disable/destroy.
1479 else
1480 {
1481 // scene objects are reset and disabled.
1482 // they always stay in the scene, we don't destroy them.
1483 if (identity.sceneId != 0)
1484 {
1485 identity.Reset();
1486 identity.gameObject.SetActive(false);
1487 }
1488 // spawned objects are destroyed
1489 else
1490 {
1491 GameObject.Destroy(identity.gameObject);
1492 }
1493 }
1494 }
1495 }
1496 }
1497 spawned.Clear();
1498 }
1499 catch (InvalidOperationException e)
1500 {
1501 Debug.LogException(e);
1502 Debug.LogError("Could not DestroyAllClientObjects because spawned list was modified during loop, make sure you are not modifying NetworkIdentity.spawned by calling NetworkServer.Destroy or NetworkServer.Spawn in OnDestroy or OnDisable.");
1503 }
1504 }
static readonly Dictionary< uint, NetworkIdentity > spawned
All spawned NetworkIdentities by netId.

◆ Disconnect()

static void Mirror.NetworkClient.Disconnect ( )
static

Disconnect from server.

Definition at line 234 of file NetworkClient.cs.

235 {
236 // only if connected or connecting.
237 // don't disconnect() again if already in the process of
238 // disconnecting or fully disconnected.
239 if (connectState != ConnectState.Connecting &&
240 connectState != ConnectState.Connected)
241 return;
242
243 // we are disconnecting until OnTransportDisconnected is called.
244 // setting state to Disconnected would stop OnTransportDisconnected
245 // from calling cleanup code because it would think we are already
246 // disconnected fully.
247 // TODO move to 'cleanup' code below if safe
248 connectState = ConnectState.Disconnecting;
249 ready = false;
250
251 // call Disconnect on the NetworkConnection
253
254 // IMPORTANT: do NOT clear connection here yet.
255 // we still need it in OnTransportDisconnected for callbacks.
256 // connection = null;
257 }
abstract void Disconnect()
Disconnects this connection.

◆ GetPrefab()

static bool Mirror.NetworkClient.GetPrefab ( Guid  assetId,
out GameObject  prefab 
)
static

Find the registered prefab for this asset id.

Definition at line 508 of file NetworkClient.cs.

509 {
510 prefab = null;
511 return assetId != Guid.Empty &&
512 prefabs.TryGetValue(assetId, out prefab) && prefab != null;
513 }

◆ PrepareToSpawnSceneObjects()

static void Mirror.NetworkClient.PrepareToSpawnSceneObjects ( )
static

Call this after loading/unloading a scene in the client after connection to register the spawnable objects

Definition at line 1158 of file NetworkClient.cs.

1159 {
1160 // remove existing items, they will be re-added below
1161 spawnableObjects.Clear();
1162
1163 // finds all NetworkIdentity currently loaded by unity (includes disabled objects)
1164 NetworkIdentity[] allIdentities = Resources.FindObjectsOfTypeAll<NetworkIdentity>();
1165 foreach (NetworkIdentity identity in allIdentities)
1166 {
1167 // add all unspawned NetworkIdentities to spawnable objects
1168 if (ConsiderForSpawning(identity))
1169 {
1170 if (spawnableObjects.TryGetValue(identity.sceneId, out NetworkIdentity existingIdentity))
1171 {
1172 string msg = $"NetworkClient: Duplicate sceneId {identity.sceneId} detected on {identity.gameObject.name} and {existingIdentity.gameObject.name}\n" +
1173 $"This can happen if a networked object is persisted in DontDestroyOnLoad through loading / changing to the scene where it originated,\n" +
1174 $"otherwise you may need to open and re-save the {identity.gameObject.scene} to reset scene id's.";
1175 Debug.LogWarning(msg, identity.gameObject);
1176 }
1177 else
1178 {
1179 spawnableObjects.Add(identity.sceneId, identity);
1180 }
1181 }
1182 }
1183 }

◆ Ready()

static bool Mirror.NetworkClient.Ready ( )
static

Sends Ready message to server, indicating that we loaded the scene, ready to enter the game.

Definition at line 923 of file NetworkClient.cs.

924 {
925 // Debug.Log($"NetworkClient.Ready() called with connection {conn}");
926 if (ready)
927 {
928 Debug.LogError("NetworkClient is already ready. It shouldn't be called twice.");
929 return false;
930 }
931
932 // need a valid connection to become ready
933 if (connection == null)
934 {
935 Debug.LogError("Ready() called with invalid connection object: conn=null");
936 return false;
937 }
938
939 // Set these before sending the ReadyMessage, otherwise host client
940 // will fail in InternalAddPlayer with null readyConnection.
941 // TODO this is redundant. have one source of truth for .ready
942 ready = true;
943 connection.isReady = true;
944
945 // Tell server we're ready to have a player object spawned
946 connection.Send(new ReadyMessage());
947 return true;
948 }

◆ RegisterHandler< T >()

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

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

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 462 of file NetworkClient.cs.

463 : struct, NetworkMessage
464 {
465 ushort msgType = MessagePacking.GetId<T>();
466 if (handlers.ContainsKey(msgType))
467 {
468 Debug.LogWarning($"NetworkClient.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
469 }
470 // we use the same WrapHandler function for server and client.
471 // so let's wrap it to ignore the NetworkConnection parameter.
472 // it's not needed on client. it's always NetworkClient.connection.
473 void HandlerWrapped(NetworkConnection _, T value) => handler(value);
474 handlers[msgType] = MessagePacking.WrapHandler((Action<NetworkConnection, T>) HandlerWrapped, requireAuthentication);
475 }

◆ RegisterPrefab() [1/6]

static void Mirror.NetworkClient.RegisterPrefab ( GameObject  prefab)
static

Register spawnable prefab.

Definition at line 589 of file NetworkClient.cs.

590 {
591 if (prefab == null)
592 {
593 Debug.LogError("Could not register prefab because it was null");
594 return;
595 }
596
597 NetworkIdentity identity = prefab.GetComponent<NetworkIdentity>();
598 if (identity == null)
599 {
600 Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component");
601 return;
602 }
603
604 RegisterPrefabIdentity(identity);
605 }

◆ RegisterPrefab() [2/6]

static void Mirror.NetworkClient.RegisterPrefab ( GameObject  prefab,
Guid  newAssetId 
)
static

Register spawnable prefab with custom assetId.

Definition at line 556 of file NetworkClient.cs.

557 {
558 if (prefab == null)
559 {
560 Debug.LogError("Could not register prefab because it was null");
561 return;
562 }
563
564 if (newAssetId == Guid.Empty)
565 {
566 Debug.LogError($"Could not register '{prefab.name}' with new assetId because the new assetId was empty");
567 return;
568 }
569
570 NetworkIdentity identity = prefab.GetComponent<NetworkIdentity>();
571 if (identity == null)
572 {
573 Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component");
574 return;
575 }
576
577 if (identity.assetId != Guid.Empty && identity.assetId != newAssetId)
578 {
579 Debug.LogError($"Could not register '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}");
580 return;
581 }
582
583 identity.assetId = newAssetId;
584
585 RegisterPrefabIdentity(identity);
586 }

◆ RegisterPrefab() [3/6]

static void Mirror.NetworkClient.RegisterPrefab ( GameObject  prefab,
Guid  newAssetId,
SpawnDelegate  spawnHandler,
UnSpawnDelegate  unspawnHandler 
)
static

Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers.

Definition at line 612 of file NetworkClient.cs.

613 {
614 // We need this check here because we don't want a null handler in the lambda expression below
615 if (spawnHandler == null)
616 {
617 Debug.LogError($"Can not Register null SpawnHandler for {newAssetId}");
618 return;
619 }
620
621 RegisterPrefab(prefab, newAssetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler);
622 }
static void RegisterPrefab(GameObject prefab, Guid newAssetId)
Register spawnable prefab with custom assetId.

◆ RegisterPrefab() [4/6]

static void Mirror.NetworkClient.RegisterPrefab ( GameObject  prefab,
Guid  newAssetId,
SpawnHandlerDelegate  spawnHandler,
UnSpawnDelegate  unspawnHandler 
)
static

Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers.

Definition at line 670 of file NetworkClient.cs.

671 {
672 if (newAssetId == Guid.Empty)
673 {
674 Debug.LogError($"Could not register handler for '{prefab.name}' with new assetId because the new assetId was empty");
675 return;
676 }
677
678 if (prefab == null)
679 {
680 Debug.LogError("Could not register handler for prefab because the prefab was null");
681 return;
682 }
683
684 NetworkIdentity identity = prefab.GetComponent<NetworkIdentity>();
685 if (identity == null)
686 {
687 Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component");
688 return;
689 }
690
691 if (identity.assetId != Guid.Empty && identity.assetId != newAssetId)
692 {
693 Debug.LogError($"Could not register Handler for '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}");
694 return;
695 }
696
697 if (identity.sceneId != 0)
698 {
699 Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene.");
700 return;
701 }
702
703 identity.assetId = newAssetId;
704 Guid assetId = identity.assetId;
705
706 if (spawnHandler == null)
707 {
708 Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
709 return;
710 }
711
712 if (unspawnHandler == null)
713 {
714 Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}");
715 return;
716 }
717
718 if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId))
719 {
720 Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'");
721 }
722
723 if (prefabs.ContainsKey(assetId))
724 {
725 // this is error because SpawnPrefab checks prefabs before handler
726 Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler");
727 }
728
729 NetworkIdentity[] identities = prefab.GetComponentsInChildren<NetworkIdentity>();
730 if (identities.Length > 1)
731 {
732 Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object.");
733 }
734
735 //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}");
736
737 spawnHandlers[assetId] = spawnHandler;
738 unspawnHandlers[assetId] = unspawnHandler;
739 }

◆ RegisterPrefab() [5/6]

static void Mirror.NetworkClient.RegisterPrefab ( GameObject  prefab,
SpawnDelegate  spawnHandler,
UnSpawnDelegate  unspawnHandler 
)
static

Register a spawnable prefab with custom spawn/unspawn handlers.

Definition at line 626 of file NetworkClient.cs.

627 {
628 if (prefab == null)
629 {
630 Debug.LogError("Could not register handler for prefab because the prefab was null");
631 return;
632 }
633
634 NetworkIdentity identity = prefab.GetComponent<NetworkIdentity>();
635 if (identity == null)
636 {
637 Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component");
638 return;
639 }
640
641 if (identity.sceneId != 0)
642 {
643 Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene.");
644 return;
645 }
646
647 Guid assetId = identity.assetId;
648
649 if (assetId == Guid.Empty)
650 {
651 Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead");
652 return;
653 }
654
655 // We need this check here because we don't want a null handler in the lambda expression below
656 if (spawnHandler == null)
657 {
658 Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
659 return;
660 }
661
662 RegisterPrefab(prefab, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler);
663 }

◆ RegisterPrefab() [6/6]

static void Mirror.NetworkClient.RegisterPrefab ( GameObject  prefab,
SpawnHandlerDelegate  spawnHandler,
UnSpawnDelegate  unspawnHandler 
)
static

Register a spawnable prefab with custom spawn/unspawn handlers.

Definition at line 743 of file NetworkClient.cs.

744 {
745 if (prefab == null)
746 {
747 Debug.LogError("Could not register handler for prefab because the prefab was null");
748 return;
749 }
750
751 NetworkIdentity identity = prefab.GetComponent<NetworkIdentity>();
752 if (identity == null)
753 {
754 Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component");
755 return;
756 }
757
758 if (identity.sceneId != 0)
759 {
760 Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene.");
761 return;
762 }
763
764 Guid assetId = identity.assetId;
765
766 if (assetId == Guid.Empty)
767 {
768 Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead");
769 return;
770 }
771
772 if (spawnHandler == null)
773 {
774 Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
775 return;
776 }
777
778 if (unspawnHandler == null)
779 {
780 Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}");
781 return;
782 }
783
784 if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId))
785 {
786 Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'");
787 }
788
789 if (prefabs.ContainsKey(assetId))
790 {
791 // this is error because SpawnPrefab checks prefabs before handler
792 Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler");
793 }
794
795 NetworkIdentity[] identities = prefab.GetComponentsInChildren<NetworkIdentity>();
796 if (identities.Length > 1)
797 {
798 Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object.");
799 }
800
801 //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}");
802
803 spawnHandlers[assetId] = spawnHandler;
804 unspawnHandlers[assetId] = unspawnHandler;
805 }

◆ RegisterSpawnHandler() [1/2]

static void Mirror.NetworkClient.RegisterSpawnHandler ( Guid  assetId,
SpawnDelegate  spawnHandler,
UnSpawnDelegate  unspawnHandler 
)
static

This is an advanced spawning function that registers a custom assetId with the spawning system.

Definition at line 837 of file NetworkClient.cs.

838 {
839 // We need this check here because we don't want a null handler in the lambda expression below
840 if (spawnHandler == null)
841 {
842 Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
843 return;
844 }
845
846 RegisterSpawnHandler(assetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler);
847 }
static void RegisterSpawnHandler(Guid assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
This is an advanced spawning function that registers a custom assetId with the spawning system.

◆ RegisterSpawnHandler() [2/2]

static void Mirror.NetworkClient.RegisterSpawnHandler ( Guid  assetId,
SpawnHandlerDelegate  spawnHandler,
UnSpawnDelegate  unspawnHandler 
)
static

This is an advanced spawning function that registers a custom assetId with the spawning system.

Definition at line 855 of file NetworkClient.cs.

856 {
857 if (spawnHandler == null)
858 {
859 Debug.LogError($"Can not Register null SpawnHandler for {assetId}");
860 return;
861 }
862
863 if (unspawnHandler == null)
864 {
865 Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}");
866 return;
867 }
868
869 if (assetId == Guid.Empty)
870 {
871 Debug.LogError("Can not Register SpawnHandler for empty Guid");
872 return;
873 }
874
875 if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId))
876 {
877 Debug.LogWarning($"Replacing existing spawnHandlers for {assetId}");
878 }
879
880 if (prefabs.ContainsKey(assetId))
881 {
882 // this is error because SpawnPrefab checks prefabs before handler
883 Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}'");
884 }
885
886 // Debug.Log("RegisterSpawnHandler asset {assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}");
887
888 spawnHandlers[assetId] = spawnHandler;
889 unspawnHandlers[assetId] = unspawnHandler;
890 }

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

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

Replace a handler for a particular message type. Should require authentication by default.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 480 of file NetworkClient.cs.

481 : struct, NetworkMessage
482 {
483 ushort msgType = MessagePacking.GetId<T>();
484 handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
485 }

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

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

Replace a handler for a particular message type. Should require authentication by default.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 490 of file NetworkClient.cs.

491 : struct, NetworkMessage
492 {
493 ReplaceHandler((NetworkConnection _, T value) => { handler(value); }, requireAuthentication);
494 }

◆ Send< T >()

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

Send a NetworkMessage to the server over the given channel.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 446 of file NetworkClient.cs.

447 : struct, NetworkMessage
448 {
449 if (connection != null)
450 {
451 if (connectState == ConnectState.Connected)
452 {
453 connection.Send(message, channelId);
454 }
455 else Debug.LogError("NetworkClient Send when not connected to a server");
456 }
457 else Debug.LogError("NetworkClient Send with no connection");
458 }

◆ Shutdown()

static void Mirror.NetworkClient.Shutdown ( )
static

Shutdown the client.

Definition at line 1509 of file NetworkClient.cs.

1510 {
1511 //Debug.Log("Shutting down client.");
1512
1513 // calls prefabs.Clear();
1514 // calls spawnHandlers.Clear();
1515 // calls unspawnHandlers.Clear();
1516 ClearSpawners();
1517
1518 // calls spawned.Clear() if no exception occurs
1520
1521 spawned.Clear();
1522 handlers.Clear();
1523 spawnableObjects.Clear();
1524
1525 // IMPORTANT: do NOT call NetworkIdentity.ResetStatics() here!
1526 // calling StopClient() in host mode would reset nextNetId to 1,
1527 // causing next connection to have a duplicate netId accidentally.
1528 // => see also: https://github.com/vis2k/Mirror/issues/2954
1529 //NetworkIdentity.ResetStatics();
1530 // => instead, reset only the client sided statics.
1531 NetworkIdentity.ResetClientStatics();
1532
1533 // disconnect the client connection.
1534 // we do NOT call Transport.Shutdown, because someone only called
1535 // NetworkClient.Shutdown. we can't assume that the server is
1536 // supposed to be shut down too!
1537 if (Transport.activeTransport != null)
1538 Transport.activeTransport.ClientDisconnect();
1539
1540 // reset statics
1541 connectState = ConnectState.None;
1542 connection = null;
1543 localPlayer = null;
1544 ready = false;
1545 isSpawnFinished = false;
1546 isLoadingScene = false;
1547
1548 unbatcher = new Unbatcher();
1549
1550 // clear events. someone might have hooked into them before, but
1551 // we don't want to use those hooks after Shutdown anymore.
1552 OnConnectedEvent = null;
1553 OnDisconnectedEvent = null;
1554 OnErrorEvent = null;
1555 }
static void ClearSpawners()
This clears the registered spawn prefabs and spawn handler functions for this client.
static void DestroyAllClientObjects()
Destroys all networked objects on the client.
static NetworkIdentity localPlayer
NetworkIdentity of the localPlayer

◆ UnregisterHandler< T >()

static bool Mirror.NetworkClient.UnregisterHandler< T > ( )
static

Unregister a message handler of type T.

Type Constraints
T :struct 
T :NetworkMessage 

Definition at line 497 of file NetworkClient.cs.

498 : struct, NetworkMessage
499 {
500 // use int to minimize collisions
501 ushort msgType = MessagePacking.GetId<T>();
502 return handlers.Remove(msgType);
503 }

◆ UnregisterPrefab()

static void Mirror.NetworkClient.UnregisterPrefab ( GameObject  prefab)
static

Removes a registered spawn prefab that was setup with NetworkClient.RegisterPrefab.

Definition at line 808 of file NetworkClient.cs.

809 {
810 if (prefab == null)
811 {
812 Debug.LogError("Could not unregister prefab because it was null");
813 return;
814 }
815
816 NetworkIdentity identity = prefab.GetComponent<NetworkIdentity>();
817 if (identity == null)
818 {
819 Debug.LogError($"Could not unregister '{prefab.name}' since it contains no NetworkIdentity component");
820 return;
821 }
822
823 Guid assetId = identity.assetId;
824
825 prefabs.Remove(assetId);
826 spawnHandlers.Remove(assetId);
827 unspawnHandlers.Remove(assetId);
828 }

◆ UnregisterSpawnHandler()

static void Mirror.NetworkClient.UnregisterSpawnHandler ( Guid  assetId)
static

Removes a registered spawn handler function that was registered with NetworkClient.RegisterHandler().

Definition at line 893 of file NetworkClient.cs.

894 {
895 spawnHandlers.Remove(assetId);
896 unspawnHandlers.Remove(assetId);
897 }

Member Data Documentation

◆ aoi

InterestManagement Mirror.NetworkClient.aoi
static

Definition at line 100 of file NetworkClient.cs.

◆ isLoadingScene

bool Mirror.NetworkClient.isLoadingScene
static

Definition at line 103 of file NetworkClient.cs.

◆ OnConnectedEvent

Action Mirror.NetworkClient.OnConnectedEvent
static

Definition at line 72 of file NetworkClient.cs.

◆ OnDisconnectedEvent

Action Mirror.NetworkClient.OnDisconnectedEvent
static

Definition at line 73 of file NetworkClient.cs.

◆ OnErrorEvent

Action<TransportError, string> Mirror.NetworkClient.OnErrorEvent
static

Definition at line 74 of file NetworkClient.cs.

◆ prefabs

readonly Dictionary<Guid, GameObject> Mirror.NetworkClient.prefabs
static
Initial value:
=
new Dictionary<Guid, GameObject>()

Registered spawnable prefabs by assetId.

Definition at line 77 of file NetworkClient.cs.

◆ ready

bool Mirror.NetworkClient.ready
static

True if client is ready (= joined world).

Definition at line 41 of file NetworkClient.cs.

◆ spawned

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

All spawned NetworkIdentities by netId.

Definition at line 29 of file NetworkClient.cs.

Property Documentation

◆ active

bool Mirror.NetworkClient.active
staticget

active is true while a client is connecting/connected

Definition at line 55 of file NetworkClient.cs.

◆ connection

NetworkConnection Mirror.NetworkClient.connection
staticgetset

Client's NetworkConnection to server.

Definition at line 33 of file NetworkClient.cs.

33{ get; internal set; }

◆ isConnected

bool Mirror.NetworkClient.isConnected
staticget

Check if client is connected (after connecting).

Definition at line 62 of file NetworkClient.cs.

◆ isConnecting

bool Mirror.NetworkClient.isConnecting
staticget

Check if client is connecting (before connected).

Definition at line 59 of file NetworkClient.cs.

◆ isHostClient

bool Mirror.NetworkClient.isHostClient
staticget

True if client is running in host mode.

Definition at line 65 of file NetworkClient.cs.

◆ localPlayer

NetworkIdentity Mirror.NetworkClient.localPlayer
staticgetset

NetworkIdentity of the localPlayer

Definition at line 44 of file NetworkClient.cs.

44{ get; internal set; }

◆ serverIp

string Mirror.NetworkClient.serverIp
staticget

IP address of the connection to server.

Definition at line 51 of file NetworkClient.cs.