Unity5.1 new network engine UNET (15th) Networking reference -- On, unity5.1unet

Source: Internet
Author: User
Tags unity network

Unity5.1 new network engine UNET (15th) Networking reference -- On, unity5.1unet

Sun Guangdong

This section provides detailed information about components used with network systems.

1. Network Animator

NetworkAnimator is used to synchronize animations across networks.

Properties
Property: Function:
Animator The Animator component on the object to be synchronized.
No Details; 2. NetworkBehaviour


NetworkBehaviours is a special script used to process NetworkIdentity components on objects. These scripts can execute HLAPI, such as Commands, ClientRPCs, SyncEvents, and SyncVars.


The NetworkIdentities of Network objects must be "spawned" in the Authority System of the Unity Network System server and the server uses NetworkServer. Spawn (). This causes them to be assigned a NetworkInstanceId, which is created on the Client Connected to the server.

Properties
Property: Function:
IsLocalPlayer True if this object is the player object for the local client.
IsServer True if this object is running on the server, and has been spawned.
IsClient True if this object is running on a client.
HasAuthority True if this object is the authoritative version of the object. So either on the server, or on the client with localPlayerAuthority.
AssetId This is the assetId of the object's NetworkIdentity.
NetId This is the netId of the object's NetworkIdentity.
PlayerControllerId This is the playerControllerId of the object's NetworkIdentity.
ConnectionToServer NetworkConnection object to use to send to the server.
ConnectionToClient

NetworkConnection object to use to send to the client.


NetworkBehaviours has the following features.

• Synchronized Variables: Synchronize Variables
• Network callbacks Network callback
• Server and Client functions
• Sending Commands Sending command
• Client rpc cils Client RPC call
• Networked Events network Events


Synchronized Variables
Synchronized Variables
NetworkBehaviours member variables can be synchronized from the server to the client. Because the server is authoritative in this system, synchronization is only in the direction from the server to the client. Customer requests are processed through the Command Commands, rather than the variables synchronized from the client.


The SyncVar attribute is used to mark member variables, such as being synchronized. SyncVars can be any basic type, not a class, list, or other set.

public class SpaceShip : NetworkBehaviour{    [SyncVar]    public int health;    [SyncVar]    public string playerName;}


The value of SyncVar is changed on the server and will be sent to all clients prepared in the game. When an object is generated, the client creates the latest state of all SyncVars from the server.


Network callbacks
Network callback


The NetworkBehaviour script for various network events calls the callback function. These are basic class virtual functions, so they can be rewritten to use such code:

public class SpaceShip : NetworkBehaviour{    public override void OnStartServer()    {        // disable client stuff    }    public override void OnStartClient()    {        // register client events, enable effects    }}


The OnStartServer function is called when an object is generated on the server or when the server starts. The OnStartClient function is called when an object is generated on the client or when the client is connected to the server for objects in the scenario. These functions are useful to do things specific to the client or server, such as the suppression effect of suppressing effects on the server, or Set Client events.

Note that when the local client is used, these two functions will be called by the same object.

Other callbacks include:
• OnSerialize-called to gather state to send from the server to clients call to collect status will be sent from the server to the client
• OnDeSerialize-called to apply state to objects on clients calls to apply state to objects on the client
• OnNetworkDestroy-called on clients when server told the object to be destroyed when the server tells the object to be destroyed to be called on the client
• OnStartLocalPlayer-called on clients for player objects for the local client (only)
• OnRebuildObservers-called on the server when the set of observers for an object is rebuild
• OnSetLocalVisibility-called on a host when the visibility of an object changes for the local client
• OnCheckObserver-called on the server to check visibility state for a new client


Server and Client functions
Server and client functions

The member functions in NetworkBehaviours can be used to customize attributes to specify them as function tags for servers only or clients only. For example:

using UnityEngine;using UnityEngine.Networking;public class SimpleSpaceShip : NetworkBehaviour{    int health;    [Server]    public void TakeDamage( int amount)    {        // will only work on server        health -= amount;    }    [Client]    void ShowExplosion()    {        // will only run on client    }    [ClientCallback]    void Update()    {        // engine invoked callback - will only run on client    }}


These attributes enable the function to return immediately if they are called when the client or server is not active. They do not generate compile-time errors, but if the call is within the range of errors, they will send a warning Log message. The attributes of ServerCallback and ClientCallback can be used for engine callback functions that cannot be controlled by user code. These attributes do not generate warnings.


Sending Commands
Send command


The command is used to request something from the client on the server. Because HLAPI is an authoritative server system, you can do things only by using commands. Run the command on the server corresponding to the player object on the client sending the command. This routing will automatically happen, and it is impossible for a different player on the client to send commands.

The Command must start with the prefix "Cmd" and have custom attributes of [Command], such:

using UnityEngine;using UnityEngine.Networking;public class SpaceShip : NetworkBehaviour{    bool alive;    float thrusting;    int spin;    [Command]    public void CmdThrust(float thrusting, int spin)    {           if (!alive)        {            this.thrusting = 0;            this.spin = 0;            return;        }                    this.thrusting = thrusting;        this.spin = spin;    }    [ClientCallback]    void Update()    {        int spin = 0;        if (Input.GetKey(KeyCode.LeftArrow))        {            spin += 1;        }        if (Input.GetKey(KeyCode.RightArrow))        {            spin -= 1;        }        // this will be called on the server        CmdThrust(Input.GetAxis("Vertical"), spin);    }}


Commands are called, usually on the client. However, instead of running a command function on the client, it will call the client Player object on the server. Therefore, commands are type-safe, with built-in security mechanisms and routing to the player, as well as effective parameter serialization mechanisms for fast calling of them.


Client RPC CILS
Client RPC call


Client RPC call is a way for a client object to do something. This is the opposite of how to use commands to send messages, but the concept is the same. Client RPC calls not only call the player object, but also can be called on any NetworkIdentity object. It must begin with "Rpc" and must be a custom attribute of [ClientRPC], as shown below:

using UnityEngine;using UnityEngine.Networking;public class SpaceShipRpc : NetworkBehaviour{    [ClientRpc]    public void RpcDoOnClient(int foo)    {        Debug.Log("OnClient " + foo);    }    [ServerCallback]    void Update()    {        int value = UnityEngine.Random.Range(0,100);        if (value < 10)        {            // this will be invoked on all clients            RpcDoOnClient(value);        }    }}

Networked Events
Network events


Network events are like client RPC calls, but not only call a function on the client object. Events on the client object will be triggered. Other scripts registered for the event are then called-the parameters are on the server, so that the client on the network interacts with each other. The Event must start with "Event" and have the Custom Attributes of SyncEvent.


Events can be used to generate powerful online game systems, and can be expanded using other scripts. This example shows how to affect the event generated by the combat script on the server on the client.

using UnityEngine;using UnityEngine.Networking;// Server scriptpublic class MyCombat : NetworkBehaviour{    public delegate void TakeDamageDelegate(int side, int damage);    public delegate void DieDelegate();    public delegate void RespawnDelegate();        float deathTimer;    bool alive;    int health;    [SyncEvent(channel=1)]    public event TakeDamageDelegate EventTakeDamage;        [SyncEvent]    public event DieDelegate EventDie;        [SyncEvent]    public event RespawnDelegate EventRespawn;    [Server]    void TakeDamage(int amount)    {        if (!alive)            return;                    if (health > amount) {            health -= amount;        }        else        {            health = 0;            alive = false;            // send die event to all clients            EventDie();            deathTimer = Time.time + 5.0f;        }    }    [ServerCallback]    void Update()    {        if (!alive)        {            if (Time.time > deathTimer)            {                Respawn();            }            return;        }    }    [Server]    void Respawn()    {        alive = true;        // send respawn event to all clients        EventRespawn();    }}

Hints
  • This is a base class that provides Commands and ClientRpc CILS.







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

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.