Unity5.1 new network engine UNET (iii) UNET NetworkManager, unity5.1unet

Source: Internet
Author: User
Tags call back class manager dedicated server

Unity5.1 new network engine UNET (iii) UNET NetworkManager, unity5.1unet

Sun Guangdong

Let's take a look at the definition of the first category: http://docs.unity3d.com/ScriptReference/Networking.NetworkManager.html

Directly inherited from MonoBehaviour, and is designed as singleton


NetworkManager is a convenient HLAPI class used to manage network systems.

You can use HLAPI to control NetworkManager for simple network applications. It provides a simple method to start and stop the client and server, as well as management scenarios, and has virtual functions. User code can be used to process network events. The NetworkManager processes a client at a time. The following example shows a minimum network setting.

using UnityEngine.Networking;public class Manager : NetworkManager {public override void OnServerConnect(NetworkConnection conn){Debug.Log ("OnPlayerConnected");}}


NetworkManager is an integral part of multiplayer games that manage the network status. It is actually implemented to fully use HLAPI, so everything it does can be used by other forms developers. However, the Network Manager encapsulates many useful functions to make it as simple as possible to create, run, and debug multiplayer games.


The Network Manager can use scripts that are not needed at all. It has an inspector control in the editor that allows you to configure all its functions. NetworkManagerHUD provides a simple and default user interface that allows users to control online games during runtime. For advanced use, developers can derive classes from the Network Manager and rewrite virtual functions to customize their behaviors.

The functions of the network manager include:
• Game State Management
• Spawning Management
• Scene Management
• Debugging Information
• Matchmaking Matching System
• Customization


Getting started NetworkManager


The network manager can be the core of multiplayer games that control components. To start, create an empty game object or select a convenient manager object in your scenario. From the Network/NetworkManager menu, add the NetworkManager component. Shows the newly added NetworkManager:



The NetworkManager inspector panel in the editor allows you to configure and control many network-related things.

NetworkManagerHUD is another component related to NetworkManager. When the game operation controls the network status, it gives you a simple user interface. This is a good entry-level knowledge network project, but cannot be used as the final ui design of the game. NetworkManagerHUD looks like:

 


A real game has a correct UI for controlling the game status and allowing players to choose a game. However, to start, we can temporarily control the game.


Game State Management


As a client, as a dedicated server, or as a "Host", the client and server are available at the same time. UNet multiplayer games can run in three modes. UNet is designed to make the same game code and assets work in all of these cases. The development of single-player games and multiplayer games should be the same thing.


The network manager has a method for entering each mode. NetworkManager. startClient (), NetworkManager. startServer () and NetworkManager. startHost () is all the available script code, so they can be called, input from the keyboard handler or custom UI events. You can select the default runtime controller to display and call these functions. There are also buttons on the NetworkManagerHUD inspector to call the same function in Play mode:


Either method is used to change the game status, networkAddress network address, or networkPort network port attribute. When the server or host is started, networkPort becomes the listening port. When the client starts, networkAddress is the address to be connected, and networkPort is the port to be connected.


Spawning Management

The network manager can be used to manage network objects from preset instantiation. Most games have the prefab as the player Object, so the network manager has a slot (field) and drag the player prefab to assign values. When a player prefab is set, the player object is automatically generated from this prefab and created for each user in the game. This applies to remote players participants on local player-hosted servers and remote clients. Note that the player prefab must have the NetworkIdentity component.


In addition to player prefab, presets of other objects will be dynamically generated but must be recorded in ClientScene. You can use the ClientScene. RegisterPrefab () function, or it can be automatically completed by the Network Manager. Adding a pre-generated list will enable them to automatically register. The inspector Field Configuration of NetworkManager looks like:


Once a player prefab is set, you should be able to start the game as a host and see that the player Object is generated. Stopping this competition should destroy the player Object. When you want to run a game with another copy and a client connected to the local host, you should make another player object appear and stop the client. The player Object of the client should be destroyed.


The player object is generated by default by NetworkManager. OnServerAddPlayer. If you want to customize the method for creating a player object, you can override the virtual function. The default implementation is similar:

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


Note that NetworkServer. AddPlayerForConnection () must be called when a player object is created. Therefore, NetworkServer. AddPlayerForConnection () is generated and associated with the client connection. This will generate the object, so NetworkServer. Spawn does not need to be a player object.

Start Positions


To control the creation of players, you can use the NetworkStartPosition component here. The Network Manager searches for the NetworkStartPosition object in the scenario. if it finds the NetworkStartPosition object, it generates the position and direction of the Player. Custom Code can access available NetworkStartPositions through the NetworkManager. startPositions list. It is also a helper function GetStartPosition () to the network manager. You can run OnServerAddPlayer to find the starting position.


Scene Management


Most games have multiple scenarios. There are at least titles or start menus and scenes for playing the game. The Network Manager is used to automatically manage the scenario status and scenario switching. It is suitable for multiplayer games. The properties Panel of the network manager has two slots: offlineScene and onlineScene. Drag and Drop scenario objects to these slots to activate network scenario management.


When the server or host is started, the online scenario is loaded. This will become the current network scenario. Any Client Connected to this server will be ordered to load this scenario. The name of this scenario is stored in the networkSceneName attribute.


When the network is stopped, the client will load offline scenarios by stopping the server or host or disconnecting. When multiplayer games are disconnected, the game is allowed to automatically return to the menu scenario.


By calling NetworkManager. ServerChangeScene (), you can change the scenario when the game is active. This will change the scenario for all clients currently connected, and update networkSceneName. New customers will also load new scenarios.


Although the scenario management of the network is active, calling the NetworkManager. StartHost () or NetworkManager. StopClient () function of any game status management function can cause scenario changes. This applies to the runtime control UI. Therefore, by setting the scenario and calling these functions, it is easy to control the flow of multiplayer games.


Note that all objects caused by changes in the scenario will be destroyed in the scenario. This may include the network manager! If you want the network manager to not be destroyed during the conversion, make sure that the "Dont Destroy On Load" attribute is set to true. In simple cases, this is the best configuration. However, it is possible that the Network Manager uses different settings in each scenario to control incremental pre-loading or switch between different scenarios.


Debugging Information


The NetworkManagerHUD property panel displays other information about the network status at runtime. This includes:


• Network Connection
• Activate the NetworkIdentity Server Object
• Activate the NetworkIdentity client object
• Client peers


In addition, the registered client message handler is displayed in the preview window.



Matchmaking Matching System


The user interface and network management inspector UI of the network manager at runtime allow interaction with matching services. The NetworkManager. StartMatchmaker () function acts as a matching interface and fills in the NetworkManager. matchmaker attribute with a NetworkMatch object. Once this is activated, the default Ui uses it and the callback function to perform simple pairing on the network manager.

Functions with a network manager with a virtual derived class can use a custom respoding to call back the behavior of matchmaker.


Custom


The virtual functions on the derived classes of the network manager can use custom behaviors. When performing these functions, you must take care of the functions provided by default. For example, in OnServerAddPlayer (), the NetworkServer. AddPlayer function must call the activated Player Object connection.


Functions called on Server/Host:

// called when a client connects public virtual void OnServerConnect(NetworkConnection conn);// called when a client disconnectspublic virtual void OnServerDisconnect(NetworkConnection conn){    NetworkServer.DestroyPlayersForConnection(conn);}// called when a client is readypublic virtual void OnServerReady(NetworkConnection conn){    NetworkServer.SetClientReady(conn);}// called when a new player is added for a clientpublic virtual void OnServerAddPlayer(NetworkConnection conn, short playerControllerId){    var player = (GameObject)GameObject.Instantiate(playerPrefab, playerSpawnPos, Quaternion.identity);    NetworkServer.AddPlayer(conn, player, playerControllerId);}// called when a player is removed for a clientpublic virtual void OnServerRemovePlayer(NetworkConnection conn, short playerControllerId){    UPlayer player;    if (conn.GetPlayer(playerControllerId, out player))    {        if (player.NetworkIdentity != null && player.NetworkIdentity.gameObject != null)            NetworkServer.Destroy(player.NetworkIdentity.gameObject);    }}// called when a network error occurspublic virtual void OnServerError(NetworkConnection conn, int errorCode);

Functions called on the client:

// called when connected to a serverpublic virtual void OnClientConnect(NetworkConnection conn){    ClientScene.Ready(conn);    ClientScene.AddPlayer(0);}// called when disconnected from a serverpublic virtual void OnClientDisconnect(NetworkConnection conn){    StopClient();}// called when a network error occurspublic virtual void OnClientError(NetworkConnection conn, int errorCode);// called when told to be not-ready by a serverpublic virtual void OnClientNotReady(NetworkConnection conn);

Functions called during Matching:

// called when a match is createdpublic virtual void OnMatchCreate(CreateMatchResponse matchInfo)// called when a list of matches is receivedpublic virtual void OnMatchList(ListMatchResponse matchList)// called when a match is joinedpublic void OnMatchJoined(JoinMatchResponse matchInfo)






Inspector

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.