NetworkManager
The NetworkManager
is a required Netcode for GameObjects (Netcode) component that has all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
NetworkManager
Inspector Properties#
- LogLevel: Sets the network logging level
- PlayerPrefab: When a Prefab is assigned, the Prefab will be instantiated as the player object and assigned to the newly connected and authorized client.
- NetworkPrefabs: Where you register your network prefabs. You can also create a single network Prefab override per registered network Prefab here.
- Protocol Version: Set this value to help distinguish between builds when the most current build has new assets that can cause issues with older builds connecting.
- Network Transport: Where your network specific settings and transport type is set. This field accepts any INetworkTransport implementation. However, unless you have unique transport specific needs UnityTransport is the recommended transport to use with Netcode for GameObjects.
- Tick Rate: This value controls the network tick update rate.
- Ensure Network Variable Length Safety: (Increases cpu processing and bandwidth) When this property is checked, Netcode for GameObjects will prevent user code from writing past the boundaries of a NetworkVariable.
- Connection Approval: This enables connection approval when this is checked and the
NetworkManager.ConnectionApprovalCallback
is assigned. - Client Connection Buffer Timeout: This value sets the amount of time that has to pass for a connecting client to complete the connection approval process. If the time specified is exceeded the connecting client will be disconnected.
- Force Same Prefabs: When checked it will always verify that connecting clients have the same registered network prefabs as the server. When not checked, Netcode for GameObjects will ignore any differences.
- Recycle Network Ids: When checked this will re-use previously assigned
NetworkObject.NetworkObjectIds
after the specified period of time. - Network Id Recycle Delay: The time it takes for a previously assigned but currently unassigned identifier to be available for use.
- Enable Scene Management: When checked Netcode for GameObjects will handle scene management and client synchronization for you. When not checked, users will have to create their own scene management scripts and handle client synchronization.
- Load Scene Time Out: When Enable Scene Management is checked, this specifies the period of time the
NetworkSceneManager
will wait while a scene is being loaded asynchronously beforeNetworkSceneManager
considers the load/unload scene event to have failed/timed out.
NetworkManager
Sub-Systems#
NetworkManager
is also where you can find references to other Netcode related management systems:
caution
All NetworkManager
sub-systems are instantiated once the NetworkManager
is started (that is, NetworkManager.IsListening == true
). A good general "rule of thumb" is to not attempt to access the below sub-systems before starting the NetworkManager
, otherwise they won't yet be initialized.
- NetworkManager.PrefabHandler: This provides access to the NetworkPrefabHandler that is used for NetworkObject pools and to have more control overriding network prefabs.
- NetworkManager.SceneManager: When scene management is enabled, this is used to load and unload scenes, register for scene events, and other scene management related actions.
- NetworkManager.SpawnManager: This handles NetworkObject spawn related functionality.
- NetworkManager.NetworkTimeSystem: a synchronized time that can be used to handle issues with latency between a client and the server.
- NetworkManager.NetworkTickSystem: Use this to adjust the frequency of when NetworkVariables are updated.
- NetworkManager.CustomMessagingManager: Use this system to create and send custom messages.
#
Starting a Server, Host, or ClientIn order to perform any netcode related action that involves sending messages, you must first have a server started and listening for connections with at least one client (a server can send RPCs to itself when running as a host) that is connected. to accomplish this, you must first start your NetworkManager
as a server, host, or client. There are three NetworkManager
methods you can invoke to accomplish this:
warning
Don't start a NetworkManager within a NetworkBehaviour's Awake method as this can lead to undesirable results depending upon your project's settings!
note
When starting a Server or joining an already started session as client, the NetworkManager
can spawn a "Player Object" belonging to the client.
For more information about player prefabs see:
#
ConnectingWhen Starting a Client, the NetworkManager
uses the IP and the Port provided in your Transport
component for connecting. While you can set the IP address in the editor, many times you might want to be able to set the IP address and port during runtime.
The below examples use Unity Transport to show a few ways you can gain access to the UnityTransport
component via the NetworkManager.Singleton
to configure your project's network settings programmatically:
If you are only setting the IP address and port number, then you can use the UnityTransport.SetConnectionData
method:
If you are using the same code block to configure both your server and your client and you want to configure your server to listen to all IP addresses assigned to it, then you can also pass a 'listen address' of "0.0.0.0" to the SetConnectionData
method, like so:
note
Using an IP address of 0.0.0.0 for the server listen address will make a server or host listen on all IP addresses assigned to the local system. This can be particularly helpful if you are testing a client instance on the same system as well as one or more client instances connecting from other systems on your local area network. Another scenario is while developing and debugging you might sometimes test local client instances on the same system and sometimes test client instances running on external systems.
It is possible to access the current connection data at runtime, via NetworkManager.Singleton.GetComponent<UnityTransport>().ConnectionData
. This will return a ConnectionAddressData
struct, holding this info. You are strongly advised to use the SetConnectionData
method to update this info.
If you are using Unity Relay to handle connections, however, don't use SetConnectionData
. The host should call SetHostRelayData
, and clients should call SetClientRelayData
. Attempting to join a Relay-hosted game via entering IP/port number (via SetConnectionData
) won't work.
More information about Netcode for GameObjects Transports
#
Disconnecting and Shutting DownDisconnecting is rather simple, but you can't use/access any subsystems (that is, NetworkSceneManager
) once the NetworkManager
is stopped because they will no longer be available. For client, host, or server modes, you only need to call the NetworkManager.Shutdown
method as it will disconnect while shutting down.
info
When no network session is active and the NetworkManager
has been shutdown, you will need to use UnityEngine.SceneManagement
to load any non-network session related scene.
#
Disconnecting Clients (Server Only)At times you might need to disconnect a client for various reasons without shutting down the server. To do this, you can call the NetworkManager.DisconnectClient
method while passing the identifier of the client you wish to disconnect as the only parameter. The client identifier can be found within:
- The
NetworkManager.ConnectedClients
dictionary that uses the client identifier as a key and the value as theNetworkClient
. - As a read only list of
NetworkClients
via theNetworkManager.ConnectedClientsList
. - A full list of all connected client identifiers can be accessed via
NetworkManager.ConnectedClientsIds
. - The client identifier is passed as a parameter to all subscribers of the
NetworkManager.OnClientConnected
event. - The player's
NetworkObject
has theNetworkObject.OwnerClientId
property.
tip
One way to get a player's primary NetworkObject
is via NetworkClient.PlayerObject
.
#
Client Disconnection NotificationsBoth the client and the server can subscribe to the NetworkManager.OnClientDisconnectCallback
event to be notified when a client is disconnected. Client disconnect notifications are "relative" to who is receiving the notification.
There are two general "disconnection" categories:
- Logical: Custom server side code (code you might have written for your project) invokes
NetworkManager.DisconnectClient
.- Example: A host player might eject a player or a player becomes "inactive" for too long.
- Network Interruption: The transport detects there is no longer a valid network connection.
When disconnect notifications are triggered:
- Clients aren'tified when they're disconnected by the server.
- The server notified if the client side disconnects (that is, a player exits a game session)
- Both the server and clients aren'tified when their network connection is disconnected (network interruption)
Scenarios where the disconnect notification won't be triggered:
- When a server "logically" disconnects a client.
- Reason: The server already knows the client is disconnected.
- When a client "logically" disconnects itself.
- Reason: The client already knows that it's disconnected.
#
Connection Notification Manager ExampleBelow is one example of how you can provide client connect and disconnect notifications to any type of NetworkBehaviour or MonoBehaviour derived component.
important
The ConnectionNotificationManager
example below should only be attached to the same GameObject as NetworkManager
to assure it persists as long as the NetworkManager.Singleton
instance.