Class NetworkManager
The NetworkManager is a convenience class for the HLAPI for managing networking systems.
For simple network applications the NetworkManager can be used to control the HLAPI. It provides simple ways to start and stop client and servers, to manage scenes, and has virtual functions that user code can use to implement handlers for network events. The NetworkManager deals with one client at a time. The example below shows a minimal network setup.
using UnityEngine;
using UnityEngine.Networking;
public class Manager : NetworkManager
{
public override void OnServerConnect(NetworkConnection conn)
{
Debug.Log("OnPlayerConnected");
}
}
Inherited Members
Namespace: UnityEngine.Networking
Syntax
[AddComponentMenu("Network/NetworkManager")]
[Obsolete("The high level API classes are deprecated and will be removed in the future.")]
public class NetworkManager : MonoBehaviour
Fields
client
The current NetworkClient being used by the manager.
This is populated when StartClient or StartLocalClient are called.
Declaration
public NetworkClient client
Field Value
Type | Description |
---|---|
NetworkClient |
isNetworkActive
True if the NetworkServer or NetworkClient isactive.
This is read-only. Calling StopServer() or StopClient() turns this off.
Declaration
public bool isNetworkActive
Field Value
Type | Description |
---|---|
Boolean |
matches
The list of matches that are available to join.
This will be populated if UMatch.ListMatches() has been called. It will contain the most recent set of results from calling ListMatches.
Declaration
public List<MatchInfoSnapshot> matches
Field Value
Type | Description |
---|---|
List<MatchInfoSnapshot> |
matchInfo
A MatchInfo instance that will be used when StartServer() or StartClient() are called.
This should be populated from the data handed to the callback for NetworkMatch.CreateMatch or NetworkMatch.JoinMatch. It contains all the information necessary to connect to the match in question.
Declaration
public MatchInfo matchInfo
Field Value
Type | Description |
---|---|
MatchInfo |
matchMaker
The UMatch MatchMaker object.
This is populated if StartMatchMaker() has been called. It is used to communicate with the matchmaking service. This should be shut down after the match is complete to clean up its internal state. If this object is null then the client is not setup to communicate with MatchMaker yet.
Declaration
public NetworkMatch matchMaker
Field Value
Type | Description |
---|---|
NetworkMatch |
matchName
The name of the current match.
A text string indicating the name of the current match in progress.
Declaration
[SerializeField]
public string matchName
Field Value
Type | Description |
---|---|
String |
matchSize
The maximum number of players in the current match.
Declaration
[SerializeField]
public uint matchSize
Field Value
Type | Description |
---|---|
UInt32 |
networkSceneName
The name of the current network scene.
This is populated if the NetworkManager is doing scene management. This should not be changed directly. Calls to ServerChangeScene() cause this to change. New clients that connect to a server will automatically load this scene.
Declaration
public static string networkSceneName
Field Value
Type | Description |
---|---|
String |
singleton
The NetworkManager singleton object.
//Create a GameObject and attach this script
//Create two buttons. To do this, go to Create>UI>Button for each.
//Click each Button in the Hierarchy, and navigate to the Inspector window. Scroll down to the On Click() section and press the + button to add an action
//Attach your GameObject to access the appropriate function you want your Button to do.
using UnityEngine;
using UnityEngine.Networking;
public class Example : NetworkManager
{
public void StartHostButton()
{
singleton.StartHost();
}
//Press the "Disconnect" Button to stop the Host
public void StopHostButton()
{
singleton.StopHost();
}
}
Declaration
public static NetworkManager singleton
Field Value
Type | Description |
---|---|
NetworkManager |
Properties
activeTransport
Declaration
public static INetworkTransport activeTransport { get; set; }
Property Value
Type | Description |
---|---|
INetworkTransport |
autoCreatePlayer
A flag to control whether or not player objects are automatically created on connect, and on scene change.
Declaration
public bool autoCreatePlayer { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
channels
The Quality-of-Service channels to use for the network transport layer.
Declaration
public List<QosType> channels { get; }
Property Value
Type | Description |
---|---|
List<QosType> |
clientLoadedScene
This is true if the client loaded a new scene when connecting to the server.
This is set before OnClientConnect is called, so it can be checked there to perform different logic if a scene load occurred.
Declaration
public bool clientLoadedScene { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
connectionConfig
The custom network configuration to use.
This will be used to configure the network transport layer.
Declaration
public ConnectionConfig connectionConfig { get; }
Property Value
Type | Description |
---|---|
ConnectionConfig |
customConfig
Flag to enable custom network configuration.
Declaration
public bool customConfig { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
defaultTransport
Declaration
public static INetworkTransport defaultTransport { get; }
Property Value
Type | Description |
---|---|
INetworkTransport |
dontDestroyOnLoad
A flag to control whether the NetworkManager object is destroyed when the scene changes.
This should be set if your game has a single NetworkManager that exists for the lifetime of the process. If there is a NetworkManager in each scene, then this should not be set.
Declaration
public bool dontDestroyOnLoad { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
globalConfig
The transport layer global configuration to be used.
This defines global settings for the operation of the transport layer.
Declaration
public GlobalConfig globalConfig { get; }
Property Value
Type | Description |
---|---|
GlobalConfig |
logLevel
The log level specifically to user for network log messages.
Declaration
public LogFilter.FilterLevel logLevel { get; set; }
Property Value
Type | Description |
---|---|
LogFilter.FilterLevel |
matchHost
The hostname of the matchmaking server.
The default address for the MatchMaker is mm.unet.unity3d.com That will connect a client to the nearest datacenter geographically. However because data centers are siloed from each other, players will only see matches occurring inside the data center they are currently connected to. If a player of your game is traveling to another part of the world, for instance, they may interact with a different set of players that are in that data center. You can override this behavior by specifying a particular data center. Keep in mind generally as distance grows so does latency, which is why we run data centers spread out over the world.
To connect to a specific data center use one of the following addresses:
United States: us1-mm.unet.unity3d.com Europe: eu1-mm.unet.unity3d.com Singapore: ap1-mm.unet.unity3d.com.
Declaration
public string matchHost { get; set; }
Property Value
Type | Description |
---|---|
String |
matchPort
The port of the matchmaking service.
Declaration
public int matchPort { get; set; }
Property Value
Type | Description |
---|---|
Int32 |
maxConnections
The maximum number of concurrent network connections to support.
The effects the memory usage of the network layer.
Declaration
public int maxConnections { get; set; }
Property Value
Type | Description |
---|---|
Int32 |
maxDelay
The maximum delay before sending packets on connections.
In seconds. The default of 0.01 seconds means packets will be delayed at most by 10 milliseconds. Setting this to zero will disable HLAPI connection buffering.
Declaration
public float maxDelay { get; set; }
Property Value
Type | Description |
---|---|
Single |
migrationManager
The migration manager being used with the NetworkManager.
Declaration
public NetworkMigrationManager migrationManager { get; }
Property Value
Type | Description |
---|---|
NetworkMigrationManager |
networkAddress
The network address currently in use.
For clients, this is the address of the server that is connected to. For servers, this is the local address.
Declaration
public string networkAddress { get; set; }
Property Value
Type | Description |
---|---|
String |
networkPort
The network port currently in use.
For clients, this is the port of the server connected to. For servers, this is the listen port.
Declaration
public int networkPort { get; set; }
Property Value
Type | Description |
---|---|
Int32 |
numPlayers
NumPlayers is the number of active player objects across all connections on the server.
This is only valid on the host / server.
Declaration
public int numPlayers { get; }
Property Value
Type | Description |
---|---|
Int32 |
offlineScene
The scene to switch to when offline.
Setting this makes the NetworkManager do scene management. This scene will be switched to when a network session is completed - such as a client disconnect, or a server shutdown.
Declaration
public string offlineScene { get; set; }
Property Value
Type | Description |
---|---|
String |
onlineScene
The scene to switch to when online.
Setting this makes the NetworkManager do scene management. This scene will be switched to when a network session is started - such as a client connect, or a server listen.
Declaration
public string onlineScene { get; set; }
Property Value
Type | Description |
---|---|
String |
packetLossPercentage
The percentage of incoming and outgoing packets to be dropped for clients.
This is only used when useSimulator is set.
Declaration
public float packetLossPercentage { get; set; }
Property Value
Type | Description |
---|---|
Single |
playerPrefab
The default prefab to be used to create player objects on the server.
Player objects are created in the default handler for AddPlayer() on the server. Implementing OnServerAddPlayer overrides this behaviour.
Declaration
public GameObject playerPrefab { get; set; }
Property Value
Type | Description |
---|---|
GameObject |
playerSpawnMethod
The current method of spawning players used by the NetworkManager.
//Attach this script to a GameObject
//This script switches the Player spawn method between Round Robin spawning and Random spawning when you press the space key in Play Mode.
using UnityEngine;
using UnityEngine.Networking;
public class Example : NetworkManager
{
void Start()
{
//Change the Player Spawn Method to be Round Robin (spawn at the spawn points in order)
playerSpawnMethod = PlayerSpawnMethod.RoundRobin;
}
void Update()
{
//Press the space key to switch the spawn method
if (Input.GetKeyDown(KeyCode.Space))
{
//Press the space key to switch from RoundRobin method to Random method (spawn at the spawn points in a random order)
if (playerSpawnMethod == PlayerSpawnMethod.RoundRobin)
playerSpawnMethod = PlayerSpawnMethod.Random;
//Otherwise switch back to RoundRobin at the press of the space key
else playerSpawnMethod = PlayerSpawnMethod.RoundRobin;
}
}
}
Declaration
public PlayerSpawnMethod playerSpawnMethod { get; set; }
Property Value
Type | Description |
---|---|
PlayerSpawnMethod |
runInBackground
Controls whether the program runs when it is in the background.
This is required when multiple instances of a program using networking are running on the same machine, such as when testing using localhost. But this is not recommended when deploying to mobile platforms.
Declaration
public bool runInBackground { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
scriptCRCCheck
Flag for using the script CRC check between server and clients.
Enables a CRC check between server and client that ensures the NetworkBehaviour scripts match. This may not be appropriate in some cases, such a when the client and server are different Unity projects.
Declaration
public bool scriptCRCCheck { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
secureTunnelEndpoint
Allows you to specify an EndPoint object instead of setting networkAddress and networkPort (required for some platforms such as Xbox One).
Setting this object overrides the networkAddress and networkPort fields, and will be used instead of making connections.
Declaration
public EndPoint secureTunnelEndpoint { get; set; }
Property Value
Type | Description |
---|---|
EndPoint |
sendPeerInfo
Declaration
[Obsolete("moved to NetworkMigrationManager")]
public bool sendPeerInfo { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
serverBindAddress
The IP address to bind the server to.
This is only used if serverBindToIP is set to true.
Declaration
public string serverBindAddress { get; set; }
Property Value
Type | Description |
---|---|
String |
serverBindToIP
Flag to tell the server whether to bind to a specific IP address.
If this is false, then no specific IP address is bound to (IP_ANY).
Declaration
public bool serverBindToIP { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
simulatedLatency
The delay in milliseconds to be added to incoming and outgoing packets for clients.
This is only used when useSimulator is set.
Declaration
public int simulatedLatency { get; set; }
Property Value
Type | Description |
---|---|
Int32 |
spawnPrefabs
List of prefabs that will be registered with the spawning system.
For each of these prefabs, ClientManager.RegisterPrefab() will be automatically invoke.
Declaration
public List<GameObject> spawnPrefabs { get; }
Property Value
Type | Description |
---|---|
List<GameObject> |
startPositions
The list of currently registered player start positions for the current scene.
Declaration
public List<Transform> startPositions { get; }
Property Value
Type | Description |
---|---|
List<Transform> |
useSimulator
Flag that control whether clients started by this NetworkManager will use simulated latency and packet loss.
Declaration
public bool useSimulator { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
useWebSockets
This makes the NetworkServer listen for WebSockets connections instead of normal transport layer connections.
This allows WebGL clients to connect to the server.
Declaration
public bool useWebSockets { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
Methods
GetStartPosition()
This finds a spawn position based on NetworkStartPosition objects in the scene.
This is used by the default implementation of OnServerAddPlayer.
Declaration
public Transform GetStartPosition()
Returns
Type | Description |
---|---|
Transform | Returns the transform to spawn a player at, or null. |
IsClientConnected()
This checks if the NetworkManager has a client and that it is connected to a server.
This is more specific than NetworkClient.isActive, which will be true if there are any clients active, rather than just the NetworkManager's client.
Declaration
public bool IsClientConnected()
Returns
Type | Description |
---|---|
Boolean | True if the NetworkManagers client is connected to a server. |
OnClientConnect(NetworkConnection)
Called on the client when connected to a server.
The default implementation of this function sets the client as ready and adds a player. Override the function to dictate what happens when the client connects.
//Attach this script to a GameObject
//Create a Text GameObject(Create>UI>Text) and attach it to the Text field in the Inspector window
//This script changes the Text depending on if a client connects or disconnects to the server
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Example : NetworkManager
{
//Assign a Text component in the GameObject's Inspector
public Text m_ClientText;
//Detect when a client connects to the Server
public override void OnClientConnect(NetworkConnection connection)
{
//Change the text to show the connection on the client side
m_ClientText.text = " " + connection.connectionId + " Connected!";
}
//Detect when a client connects to the Server
public override void OnClientDisconnect(NetworkConnection connection)
{
//Change the text to show the connection loss on the client side
m_ClientText.text = "Connection" + connection.connectionId + " Lost!";
}
}
Declaration
public virtual void OnClientConnect(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection to the server. |
OnClientDisconnect(NetworkConnection)
Called on clients when disconnected from a server.
This is called on the client when it disconnects from the server. Override this function to decide what happens when the client disconnects.
//Attach this script to a GameObject
//Create a Text GameObject(Create>UI>Text) and attach it to the Text field in the Inspector window
//This script changes the Text depending on if a client connects or disconnects to the server
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class OnClientConnectExample : NetworkManager
{
//Assign a Text component in the GameObject's Inspector
public Text m_ClientText;
//Detect when a client connects to the Server
public override void OnClientConnect(NetworkConnection connection)
{
//Change the text to show the connection on the client side
m_ClientText.text = " " + connection.connectionId + " Connected!";
}
//Detect when a client connects to the Server
public override void OnClientDisconnect(NetworkConnection connection)
{
//Change the text to show the connection loss on the client side
m_ClientText.text = "Connection" + connection.connectionId + " Lost!";
}
}
Declaration
public virtual void OnClientDisconnect(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection to the server. |
OnClientError(NetworkConnection, Int32)
Called on clients when a network error occurs.
Declaration
public virtual void OnClientError(NetworkConnection conn, int errorCode)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection to a server. |
Int32 | errorCode | Error code. |
OnClientNotReady(NetworkConnection)
Called on clients when a servers tells the client it is no longer ready.
This is commonly used when switching scenes.
Declaration
public virtual void OnClientNotReady(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection to a server. |
OnClientSceneChanged(NetworkConnection)
Called on clients when a scene has completed loaded, when the scene load was initiated by the server.
Scene changes can cause player objects to be destroyed. The default implementation of OnClientSceneChanged in the NetworkManager is to add a player object for the connection if no player object exists.
Declaration
public virtual void OnClientSceneChanged(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | The network connection that the scene change message arrived on. |
OnDestroyMatch(Boolean, String)
Callback that happens when a NetworkMatch.DestroyMatch request has been processed on the server. ///
Declaration
public virtual void OnDestroyMatch(bool success, string extendedInfo)
Parameters
Type | Name | Description |
---|---|---|
Boolean | success | Indicates if the request succeeded. |
String | extendedInfo | A text description for the error if success is false. |
OnDropConnection(Boolean, String)
Callback that happens when a NetworkMatch.DropConnection match request has been processed on the server.
Declaration
public virtual void OnDropConnection(bool success, string extendedInfo)
Parameters
Type | Name | Description |
---|---|---|
Boolean | success | Indicates if the request succeeded. |
String | extendedInfo | A text description for the error if success is false. |
OnMatchCreate(Boolean, String, MatchInfo)
Callback that happens when a NetworkMatch.CreateMatch request has been processed on the server.
Declaration
public virtual void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
Parameters
Type | Name | Description |
---|---|---|
Boolean | success | Indicates if the request succeeded. |
String | extendedInfo | A text description for the error if success is false. |
MatchInfo | matchInfo | The information about the newly created match. |
OnMatchJoined(Boolean, String, MatchInfo)
Callback that happens when a NetworkMatch.JoinMatch request has been processed on the server.
Declaration
public virtual void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
Parameters
Type | Name | Description |
---|---|---|
Boolean | success | Indicates if the request succeeded. |
String | extendedInfo | A text description for the error if success is false. |
MatchInfo | matchInfo | The info for the newly joined match. |
OnMatchList(Boolean, String, List<MatchInfoSnapshot>)
Callback that happens when a NetworkMatch.ListMatches request has been processed on the server.
Declaration
public virtual void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matchList)
Parameters
Type | Name | Description |
---|---|---|
Boolean | success | Indicates if the request succeeded. |
String | extendedInfo | A text description for the error if success is false. |
List<MatchInfoSnapshot> | matchList | A list of matches corresponding to the filters set in the initial list request. |
OnServerAddPlayer(NetworkConnection, Int16)
Declaration
public virtual void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | |
Int16 | playerControllerId |
OnServerAddPlayer(NetworkConnection, Int16, NetworkReader)
Called on the server when a client adds a new player with ClientScene.AddPlayer.
The default implementation for this function creates a new player object from the playerPrefab.
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;
class MyManager : NetworkManager
{
public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader)
{
if (extraMessageReader != null)
{
var s = extraMessageReader.ReadMessage<StringMessage>();
Debug.Log("my name is " + s.value);
}
OnServerAddPlayer(conn, playerControllerId, extraMessageReader);
}
}
Declaration
public virtual void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection from client. |
Int16 | playerControllerId | Id of the new player. |
NetworkReader | extraMessageReader | An extra message object passed for the new player. |
OnServerConnect(NetworkConnection)
Called on the server when a new client connects.
Unity calls this on the Server when a Client connects to the Server. Use an override to tell the NetworkManager what to do when a client connects to the server.
//Attach this script to a GameObject and add a NetworkHUD component to the GameObject.
//Create a Text GameObject (Create>UI>Text) and attach it in the Text field in the Inspector.
//This script changes Text on the screen when a client connects to the server
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class OnServerConnectExample : NetworkManager
{
//Assign a Text component in the GameObject's Inspector
public Text m_Text;
//Detect when a client connects to the Server
public override void OnServerConnect(NetworkConnection connection)
{
//Change the text to show the connection and the client's ID
m_Text.text = "Client " + connection.connectionId + " Connected!";
}
}
Declaration
public virtual void OnServerConnect(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection from client. |
OnServerDisconnect(NetworkConnection)
Called on the server when a client disconnects.
This is called on the Server when a Client disconnects from the Server. Use an override to decide what should happen when a disconnection is detected.
//This script outputs a message when a client connects or disconnects from the server
//Attach this script to your GameObject.
//Attach a NetworkManagerHUD to your by clicking Add Component in the Inspector window of the GameObject. Then go to Network>NetworkManagerHUD.
//Create a Text GameObject and attach it to the Text field in the Inspector.
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Example : NetworkManager
{
//Assign a Text component in the GameObject's Inspector
public Text m_Text;
//Detect when a client connects to the Server
public override void OnServerConnect(NetworkConnection connection)
{
//Change the text to show the connection
m_Text.text = "Client " + connection.connectionId + " Connected!";
}
//Detect when a client disconnects from the Server
public override void OnServerDisconnect(NetworkConnection connection)
{
//Change the text to show the loss of connection
m_Text.text = "Client " + connection.connectionId + "Connection Lost!";
}
}
Declaration
public virtual void OnServerDisconnect(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection from client. |
OnServerError(NetworkConnection, Int32)
Called on the server when a network error occurs for a client connection.
Declaration
public virtual void OnServerError(NetworkConnection conn, int errorCode)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection from client. |
Int32 | errorCode | Error code. |
OnServerReady(NetworkConnection)
Called on the server when a client is ready.
The default implementation of this function calls NetworkServer.SetClientReady() to continue the network setup process.
Declaration
public virtual void OnServerReady(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Connection from client. |
OnServerRemovePlayer(NetworkConnection, PlayerController)
Called on the server when a client removes a player.
The default implementation of this function destroys the corresponding player object.
Declaration
public virtual void OnServerRemovePlayer(NetworkConnection conn, PlayerController player)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | The connection to remove the player from. |
PlayerController | player | The player controller to remove. |
OnServerSceneChanged(String)
Called on the server when a scene is completed loaded, when the scene load was initiated by the server with ServerChangeScene().
Declaration
public virtual void OnServerSceneChanged(string sceneName)
Parameters
Type | Name | Description |
---|---|---|
String | sceneName | The name of the new scene. |
OnSetMatchAttributes(Boolean, String)
Callback that happens when a NetworkMatch.SetMatchAttributes has been processed on the server.
Declaration
public virtual void OnSetMatchAttributes(bool success, string extendedInfo)
Parameters
Type | Name | Description |
---|---|---|
Boolean | success | Indicates if the request succeeded. |
String | extendedInfo | A text description for the error if success is false. |
OnStartClient(NetworkClient)
This is a hook that is invoked when the client is started.
StartClient has multiple signatures, but they all cause this hook to be called.
Declaration
public virtual void OnStartClient(NetworkClient client)
Parameters
Type | Name | Description |
---|---|---|
NetworkClient | client | The NetworkClient object that was started. |
OnStartHost()
This hook is invoked when a host is started.
StartHost has multiple signatures, but they all cause this hook to be called.
Declaration
public virtual void OnStartHost()
OnStartServer()
This hook is invoked when a server is started - including when a host is started. StartServer has multiple signatures, but they all cause this hook to be called.
Declaration
public virtual void OnStartServer()
OnStopClient()
This hook is called when a client is stopped.
Declaration
public virtual void OnStopClient()
OnStopHost()
This hook is called when a host is stopped.
Declaration
public virtual void OnStopHost()
OnStopServer()
This hook is called when a server is stopped - including when a host is stopped.
Declaration
public virtual void OnStopServer()
RegisterStartPosition(Transform)
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.
Declaration
public static void RegisterStartPosition(Transform start)
Parameters
Type | Name | Description |
---|---|---|
Transform | start | Transform to register. |
ServerChangeScene(String)
This causes the server to switch scenes and sets the networkSceneName.
Clients that connect to this server will automatically switch to this scene. This is called autmatically if onlineScene or offlineScene are set, but it can be called from user code to switch scenes again while the game is in progress. This automatically sets clients to be not-ready. The clients must call NetworkClient.Ready() again to participate in the new scene.
Declaration
public virtual void ServerChangeScene(string newSceneName)
Parameters
Type | Name | Description |
---|---|---|
String | newSceneName | The name of the scene to change to. The server will change scene immediately, and a message will be sent to connected clients to ask them to change scene also. |
SetMatchHost(String, Int32, Boolean)
This sets the address of the MatchMaker service.
The default address for the MatchMaker is mm.unet.unity3d.com That will connect a client to the nearest datacenter geographically. However because data centers are siloed from each other, players will only see matches occurring inside the data center they are currently connected to. If a player of your game is traveling to another part of the world, for instance, they may interact with a different set of players that are in that data center. You can override this behavior by specifying a particular data center. Keep in mind generally as distance grows so does latency, which is why we run data centers spread out over the world.
To connect to a specific data center use one of the following addresses:
United States: us1-mm.unet.unity3d.com Europe: eu1-mm.unet.unity3d.com Singapore: ap1-mm.unet.unity3d.com.
Declaration
public void SetMatchHost(string newHost, int port, bool https)
Parameters
Type | Name | Description |
---|---|---|
String | newHost | Hostname of MatchMaker service. |
Int32 | port | Port of MatchMaker service. |
Boolean | https | Protocol used by MatchMaker service. |
SetupMigrationManager(NetworkMigrationManager)
This sets up a NetworkMigrationManager object to work with this NetworkManager.
The NetworkManager will automatically call functions on the migration manager, such as NetworkMigrationManager.LostHostOnClient when network events happen.
Declaration
public void SetupMigrationManager(NetworkMigrationManager man)
Parameters
Type | Name | Description |
---|---|---|
NetworkMigrationManager | man | The migration manager object to use with the NetworkManager. |
Shutdown()
Shuts down the NetworkManager completely and destroy the singleton.
This is required if a new NetworkManager instance needs to be created after the original one was destroyed. The example below has a reference to the GameObject with the NetworkManager on it and destroys the instance before calling Shutdown() and switching scenes.
using UnityEngine;
using UnityEngine.Networking;
public class SwitchToEmptyScene : MonoBehaviour
{
public GameObject NetworkManagerGameObject;
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 200, 20), "Switch"))
{
Destroy(NetworkManagerGameObject);
NetworkManager.Shutdown();
Application.LoadLevel("empty");
}
}
}
This cleanup allows a new scene with a new NetworkManager to be loaded.
Declaration
public static void Shutdown()
StartClient()
This starts a network client. It uses the networkAddress and networkPort properties as the address to connect to.
This makes the newly created client connect to the server immediately.
Declaration
public NetworkClient StartClient()
Returns
Type | Description |
---|---|
NetworkClient | The client object created. |
StartClient(MatchInfo)
Declaration
public NetworkClient StartClient(MatchInfo matchInfo)
Parameters
Type | Name | Description |
---|---|---|
MatchInfo | matchInfo |
Returns
Type | Description |
---|---|
NetworkClient |
StartClient(MatchInfo, ConnectionConfig)
Declaration
public NetworkClient StartClient(MatchInfo info, ConnectionConfig config)
Parameters
Type | Name | Description |
---|---|---|
MatchInfo | info | |
ConnectionConfig | config |
Returns
Type | Description |
---|---|
NetworkClient |
StartClient(MatchInfo, ConnectionConfig, Int32)
Declaration
public NetworkClient StartClient(MatchInfo info, ConnectionConfig config, int hostPort)
Parameters
Type | Name | Description |
---|---|---|
MatchInfo | info | |
ConnectionConfig | config | |
Int32 | hostPort |
Returns
Type | Description |
---|---|
NetworkClient |
StartHost()
This starts a network "host" - a server and client in the same application.
The client returned from StartHost() is a special "local" client that communicates to the in-process server using a message queue instead of the real network. But in almost all other cases, it can be treated as a normal client.
Declaration
public virtual NetworkClient StartHost()
Returns
Type | Description |
---|---|
NetworkClient | The client object created - this is a "local client". |
StartHost(ConnectionConfig, Int32)
Declaration
public virtual NetworkClient StartHost(ConnectionConfig config, int maxConnections)
Parameters
Type | Name | Description |
---|---|---|
ConnectionConfig | config | |
Int32 | maxConnections |
Returns
Type | Description |
---|---|
NetworkClient |
StartHost(MatchInfo)
Declaration
public virtual NetworkClient StartHost(MatchInfo info)
Parameters
Type | Name | Description |
---|---|---|
MatchInfo | info |
Returns
Type | Description |
---|---|
NetworkClient |
StartMatchMaker()
This starts MatchMaker for the NetworkManager.
This uses the matchHost and matchPort properties as the address of the MatchMaker service to connect to. Please call SetMatchHost prior to calling this function if you are not using the default MatchMaker address.
Declaration
public void StartMatchMaker()
StartServer()
This starts a new server.
This uses the networkPort property as the listen port.
//This is a script that creates a Toggle that you enable to start the Server.
//Attach this script to an empty GameObject
//Create a Toggle GameObject by going to Create>UI>Toggle.
//Click on your empty GameObject.
//Click and drag the Toggle GameObject from the Hierarchy to the Toggle section in the Inspector window.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
//This makes the GameObject a NetworkManager GameObject
public class Example : NetworkManager
{
public Toggle m_Toggle;
Text m_ToggleText;
void Start()
{
//Fetch the Text of the Toggle to allow you to change it later
m_ToggleText = m_Toggle.GetComponentInChildren<Text>();
OnOff(false);
}
//Connect this function to the Toggle to start and stop the Server
public void OnOff(bool change)
{
//Detect when the Toggle returns false
if (change == false)
{
//Stop the Server
StopServer();
//Change the text of the Toggle
m_ToggleText.text = "Connect Server";
}
//Detect when the Toggle returns true
if (change == true)
{
//Start the Server
StartServer();
//Change the Toggle Text
m_ToggleText.text = "Disconnect Server";
}
}
//Detect when the Server starts and output the status
public override void OnStartServer()
{
//Output that the Server has started
Debug.Log("Server Started!");
}
//Detect when the Server stops
public override void OnStopServer()
{
//Output that the Server has stopped
Debug.Log("Server Stopped!");
}
}
Declaration
public bool StartServer()
Returns
Type | Description |
---|---|
Boolean | True is the server was started. |
StartServer(ConnectionConfig, Int32)
Declaration
public bool StartServer(ConnectionConfig config, int maxConnections)
Parameters
Type | Name | Description |
---|---|---|
ConnectionConfig | config | |
Int32 | maxConnections |
Returns
Type | Description |
---|---|
Boolean |
StartServer(MatchInfo)
Declaration
public bool StartServer(MatchInfo info)
Parameters
Type | Name | Description |
---|---|---|
MatchInfo | info |
Returns
Type | Description |
---|---|
Boolean |
StopClient()
Stops the client that the manager is using.
Declaration
public void StopClient()
StopHost()
This stops both the client and the server that the manager is using.
Declaration
public void StopHost()
StopMatchMaker()
Stops the MatchMaker that the NetworkManager is using.
This should be called after a match is complete and before starting or joining a new match.
Declaration
public void StopMatchMaker()
StopServer()
Stops the server that the manager is using.
Declaration
public void StopServer()
UnRegisterStartPosition(Transform)
Unregisters the transform of a game object as a player spawn location.
This is done automatically by the NetworkStartPosition component, but can be done manually from user code.
Declaration
public static void UnRegisterStartPosition(Transform start)
Parameters
Type | Name | Description |
---|---|---|
Transform | start |
UseExternalClient(NetworkClient)
This allows the NetworkManager to use a client object created externally to the NetworkManager instead of using StartClient().
The StartClient() function creates a client object, but this is not always what is desired. UseExternalClient allows a NetworkClient object to be created by other code and used with the NetworkManager.
The client object will have the standard NetworkManager message handlers registered on it.
Declaration
public void UseExternalClient(NetworkClient externalClient)
Parameters
Type | Name | Description |
---|---|---|
NetworkClient | externalClient | The NetworkClient object to use. |