Using the NetworkManager


The NetworkManager is acomponent for managing the network state of a multiplayer game. It is actuallyimplemented entirely using the HLAPI, so everything it does is available todevelopers in other forms. However the NetworkManager wraps up a lot of usefulfunctionality into a single place and makes creating, running and debuggingmultiplayer games as simple as possible.

NetworkManager(网络工程管理器)是一个用来管理多人在线游戏网络状态的组件。他实际上是完全使用HLAPI(High Level API网络高级编程接口)来实现的,开发者也能用它来做其他形式的网络编程。NetworkManager封装了很多很有用的方法来让创建、运行、调试多人在线游戏变得非常的简单可行。

The NetworkManager can beused entirely without scripting. It has inspector controls in the editor thatallow configuration of all of its features. The NetworkManagerHUD supplies asimple, default user interface at runtime that allows the network game to becontrolled by the user. For advanced uses, developers can derive a class fromNetworkManager and customize its behaviour by overriding any of the virtualfunction hooks that it provides.


The NetworkManager featuresinclude:


. Game State Management

. Spawning Management

. Scene Management

. Debugging Information

. Matchmaking

. Customization







Getting Started with NetworkManager


The NetworkManager can beused as the core controlling component of a multiplayer game. To get started,create an empty game object in your starting scene, or pick a convenientmanager object. Then add the NetworkManager component from the Network/NetworkManagermenu item. The newly added NetworkManager component should look something like:



The inspector for theNetworkManager in the editor allows you to configure and control many thingsrelated to networking.


The NetworkManagerHUD isanother component that works with the NetworkManager. It gives you a simpleuser interface when the game is running to control the network state. This isgood for getting started with a network project, but not intended to be used asthe final UI for a game. The NetworkManagerHUD looks like:



Real games will have a properuser interface for controlling the game state and to allow players to choosewhat kind of game to play. But, to get started, we can use this to control thegame.


Game State Management


A Networking multiplayer gamecan run in three modes - as a client, as a dedicated server, or as a “Host”which is both a client and a server at the same time. Networking is designed tomake the same game code and assets work in all of these cases. Developing forthe single player version of the game and the multiplayer version of the gameshould be the same thing.

一个联网多人游戏可以以三种模式来运行 – 客户端,服务器,还有一个同时兼有服务器与客户端的“主机”。联网工程就是设计一个能够在这三种情况下保持有同样代码同样资源的工作。开发单人游戏版本和多人游戏版本实际上并没有太大的差别。

NetworkManager has methodsfor entering each of these modes. NetworkManager.StartClient(),NetworkManager.StartServer() and NetworkManager.StartHost() are all availableto script code, so they can be invoked from keyboard input handlers or fromcustom user interfaces. The default runtime controls that can optionally bedisplayed also invoke these same functions. There are also buttons in theNetworkManagerHUD inspector available when in play mode that call the samefunctions:




Whatever method is used tochange the game state, the properties networkAddress and networkPort are used.When a server or host is started, networkPort becomes the listen port. When aclient is started, networkAddress is the address to connect to, and networkPortis the port to connect to.


Spawning Management


The NetworkManager can beused to manage spawning of networked objects from prefabs. Most games have aprefab used as the main player object, so the NetworkManager has a slot to dragthe player prefab. When a player prefab is set, a player object will automaticallybe spawned from that prefab for each user in the game. This applies to thelocal player on a hosted server, and remote players on remote clients. Notethat the player prefab must have the NetworkIdentity component on it.


In addition to the playerprefab, the prefabs of other objects that will be dynamically spawned must beregistered with the ClientScene. This can be done with theClientScene.RegisterPrefab() functions, or it can be done by the NetworkManagerautomatically. Adding prefabs to the spawn list will make them beauto-registered. The spawn configuration section of the NetworkManagerinspector looks like:



Once a player prefab is set,you should be able to start the game as a host and see the player object bespawned. Stopping the game should make the player object be destroyed. Runninganother copy of the game and connecting as a client to localhost should makeanother player object appear, and stopping that client should make thatclient’s player object be destroyed.


The player object is spawnedby the default implementation of NetworkManager.OnServerAddPlayer. If you wantto customize the way player objects are created, you can override that virtualfunction. The default implementation is something like:


public virtual voidOnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    var player =(GameObject)GameObject.Instantiate(playerPrefab, playerSpawnPos,Quaternion.identity);
    NetworkServer.AddPlayerForConnection(conn,player, playerControllerId);

Note that the functionNetworkServer.AddPlayerForConnection() must be called for the newly createdplayer object so that it is spawned and associated with the client’s connection.This will Spawn the object, so NetworkServer.Spawn does not need to be calledfor the player object.


Start Positions


To control where players arespawned, you can use the NetworkStartPosition component. The NetworkManagerlooks for NetworkStartPosition objects in a scene, and if it finds any, then itwill spawn player at the position and orientation of one of them. Custom codecan access the available NetworkStartPositions by the listNetworkManager.startPositions, and there is also a helper functionGetStartPosition() on the NetworkManager that can be used in implementation ofOnServerAddPlayer to find a start position.


To use start positions,attach a NetworkStartPosition component to an object in the play scene. Therecan be multiple start positions within a scene. The NetworkManager will thenregister the position and orientation of the object as a start position. When aclient joins the game and a player is added, the player object will be createdat one of the start positions, with the same position and orientation.


The NetworkManager has aproperty PlayerSpawnMethod which allows configuration of how start positionsare chosen.


Scene Management


Most games have more than onescene. At very least there is usually a title screen or starting menu scene inaddition to the scene where the game is actually played. The NetworkManager issetup to automatically manage scene state and scene transitions in a way thatworks for a multiplayer game. There are two slots on the NetworkManagerinspector, the offlineScene and the onlineScene. Dragging scene objects intothese slots activates networked scene management.


When a server or host isstarted, the online scene will be loaded. This will then become the currentnetwork scene. Any clients that connect to that server will be instructed toalso load that scene. The name of this scene is stored in the networkSceneNameproperty.


When the network is stopped,by stopping the server or host, or by a client disconnecting, the offline scenewill be loaded. This allows the game to automatically return to a menu scenewhen disconnected from a multiplayer game.


You can also change sceneswhile the game is active by calling NetworkManager.ServerChangeScene(). Thiswill make all the currently connected clients change scene too, and will updatenetworkSceneName so that new clients will also load the new scene.


While networked scenemanagement is active, any calls to game state managerment functions suchNetworkManager.StartHost() or NetworkManager.StopClient() can cause scenechanges. This applies to the runtime control UI. So by setting up scenes andcalling these functions it is easy to control the flow of a multiplayer game.


Note that scene changes causeall the objects in the scene to be destroyed. This could include theNetworkManager! If you want the NetworkManager to persist between scenes, thenensure the “Dont Destroy On Load” checked boxed is set to true. In simplecases, this is the best configuration. But, it is possible to have aNetworkManager in each scene with different settings to control incrementalprefab loading, or different scene transitions.

注意,场景切换的时候,场景中所有的对象将会被销毁。可能会包含NetworkManager!如果你希望NetworkManager在各个场景中一直保留,确保“Don’t Destroy OnLoad”(加载时不销毁)勾选项是被勾选的。在一个简单的例子中,这是最好的配置。但是,这可能会导致有不同设置的NetworkManager在每个场景中越来越多,或者在不同场景切换的时候越来越多。

Debugging Information


The NetworkManagerHUDinspector panel shows additional information about the state of the network atruntime. This includes:


. network connections

. active NetworkIdentityserver objects

. active NetworkIdentityclient objects

. client peers

. 网络的连接

. 激活的服务器对象的身份证信息

. 激活的客户端对象的身份证信息

. 客户端节点

Also, registered clientmessage handlers are shown in the preview window.





The NetworkManager runtime UIand NetworkManager inspector UI allow interactions with the matchmaker service.The function NetworkManager.StartMatchmaker() enables matchmaking, andpopulates the NetworkManager.matchmaker property with a NetworkMatch object.Once this is active, the default UIs use it and callback functions onNetworkManager to let you perform simple matchmaking.


There are virtual functionson NetworkManager that derived classes can use to customize behaviour ofresponding to matchmaker callbacks.





There are virtual functionson NetworkManager that derived classes can use to customize behaviour. Whenimplementing these functions, be sure to take care of the functionality thatthe default implementations provide. For example, in OnServerAddPlayer(), thefunction NetworkServer.AddPlayer must be called to active the player object forthe connection.


Functions invoked on theServer/Host:


// called when a clientconnects 
public virtual void OnServerConnect(NetworkConnectionconn);
// called when a clientdisconnects
// 客户端断开连接时调用
public virtual voidOnServerDisconnect(NetworkConnection conn)
// called when a client isready
// 客户端准备好的时候调用
public virtual voidOnServerReady(NetworkConnection conn)
// called when a new playeris added for a client
// 在一个新玩家客户端加入时调用
public virtual voidOnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    var player =(GameObject)GameObject.Instantiate(playerPrefab, playerSpawnPos,Quaternion.identity);
    NetworkServer.AddPlayerForConnection(conn,player, playerControllerId);
// called when a player isremoved for a client
// 在玩家客户端被移除时调用
public virtual voidOnServerRemovePlayer(NetworkConnection conn, short playerControllerId)
    PlayerController player;
    if (conn.GetPlayer(playerControllerId, outplayer))
        if (player.NetworkIdentity != null&& player.NetworkIdentity.gameObject != null)
// called when a networkerror occurs
// 当有网络连接发生错误时调用
public virtual voidOnServerError(NetworkConnection conn, int errorCode);

Functions invoked on theClient:


// called when connected to aserver
// 在连接到服务器时调用
public virtual voidOnClientConnect(NetworkConnection conn)
// called when disconnectedfrom a server
// 在断开与服务器的连接时调用
public virtual voidOnClientDisconnect(NetworkConnection conn)
// called when a networkerror occurs
// 在连接发生错误时调用
public virtual voidOnClientError(NetworkConnection conn, int errorCode);
// called when told to benot-ready by a server
// 在被告知服务器未准备好时调用
public virtual voidOnClientNotReady(NetworkConnection conn);

Functions invoked for theMatchmaker:


// called when a match iscreated
// 在匹配被创建时调用
public virtual voidOnMatchCreate(CreateMatchResponse matchInfo)
// called when a list ofmatches is received
// 在收到匹配列表时调用
public virtual voidOnMatchList(ListMatchResponse matchList)
// called when a match isjoined
// 在加入比赛时调用
public voidOnMatchJoined(JoinMatchResponse matchInfo)