UNet Introduction to common concepts

  • Spawn: Simply speaking , Put... On the server GameObject, According to the above NetworkIdentity Component finds the corresponding monitoring connection , Generate the corresponding... In the monitor connection GameObject.

  • Command: Client calls , Server execution , In this way, the parameters called by the client must be UNet Serializable , In this way, the server can deserialize the parameters at execution time . We need to pay attention to , You need to have permission on the client side NetworkIdentity Component Command command .

  • ClientRpc: Server call , Client execution , ditto , The server's parameters are serialized to the client for execution , Generally speaking , The server will find the above NetworkIdentity Components , Make sure those clients are monitoring this NetworkIdentity,Rpc The command will be sent to all monitoring clients .

  • Server/ServerCallback: Only on the server side ,Callback yes Unity Internal function .

  • Client/ClientCallback: ditto , Run only on the client side ,Callback yes Unity Internal function .

  • SyncVar: The value of the server can be automatically synchronized to the client , Keep the client value the same as the server . Changes in client values do not affect server values .

Most of the above features will be translated into corresponding MsgType, Where the server calls , Client execution correspondence MsgType Like a Spawn,ClientRpc,SyncVar Corresponding MsgType Respectively ObjectSpawn,Rpc,UpdateVars, These are all NetworkServer call , The client gets the corresponding message , Execute the corresponding method . Client calls , The server performs MsgType Like a Command, The client sends , After the server detects the corresponding message, it executes .

UNet Introduction to main categories

  1. NetworkIdentity Components Introduce : The most basic components of network objects , The client and the server confirm whether it is an object (netID), It is also used to represent various states , If it is a server , Is it a client , Is there permission , Is it a local player . A simple example ,A yes Host( It's the server again , It's the client again ),B It's a Client,A And B Each has one player PlayA And PlayB. In the machine A On ,playA And playB isServer by true,isClent by true, among playA Have permission , It's a local player ,B No authority , I'm not a local player . In the machine B On ,playA And playB isServer by false,isClent by true, among playB Have permission , It's a local player ,A No authority , I'm not a local player .A And B Upper PlayA Of netID identical ,A And B Upper PlayB Of netID Also the same , among netID It means that they are the same network object on different machines .

In the following, we use network objects to represent objects with NetworkIdentity Component's GameObject.

  1. NetworkConnection: Define a connection between the client and the server , Contains the current client monitoring those network objects on the server , And encapsulating messages sent and received to the server .

  2. NetworkClient: Mainly holding current NetworkConnection Object and all NetworkClient List of static objects , Handle some messages from the default client .

  3. Monitor on network objects It's one or more NetworkConnection, It is used to indicate that one or more clients keep monitoring this network object , So when the network object is updated on the server , Will automatically update the corresponding network objects for all monitors .

  4. NetworkScene: Simply speaking ,1Server And Client Need to maintain a list of network objects ,Server Can traverse all network objects, send messages, etc , And maintain Server And Client Internet objects on the Internet stay in sync , And the client record needs to be registered prefab list . among NetworkServer And ClientScene All contain a NetworkScene object , Reference network object list .

  5. NetworkServer: Mainly holding one NetworkScene And do something that you can only do on the server for network services , Such as spawn, destory etc. . And maintain all client connections .

  6. ClientScene: Mainly hold a static NetworkScene object , For registering network objects prefab list , And the list of existing network objects on the client scene , Handle SyncVar,Rpc,SyncEvent Characteristics, etc. , And also, and ObjectSpawn,objectDestroy,objectHide News, etc. .

UNet Problems in time

problem 1 spawn What happened? , Why should the client register the corresponding prefab.

  1. When the server spawn A network object , Network object call OnStartServer, Distribute netID. And register to the NetworkScene In the list of network objects , Update as isServer by true Etc .

  2. Find all client connections , See if each client connection needs to monitor this network object , If true, Then send a message to the client MsgType.ObjectSpawn or MsgType.ObjectSpawnScene( This is usually called automatically after the service scenario changes ), And pass the message above netID.

  3. When the client receives ObjectSpawn news , It will be registered at prefab Search in , After finding Instantiate A network object , When you receive ObjectSpawnScene when , I'll look up this network object in the scene , And then all registered to ClientScene Inside NetworkScene In the list of network objects , And update the netID Same as the server . Update as isClent by true Etc .

    We manually spawn An object , It's called ObjectSpawn news , The client receives this message and gets a assetID, We have to rely on prefabe Instance a new object , Only the client has registered the corresponding prefabe Information can be used according to the corresponding assetID find prefabe.

problem 2 NetworkIdentity Of netID What does it mean , At that time, it was distributed .

When the server and client netID identical , It means they are the same object , The corresponding signs are as follows SyncVar, The server has changed , Corresponding to the same netID Internet objects in the Internet , Update to data on server ,Rpc,Commandg It's usually the same netID Call between .

Allocation usually takes place on the server spawn A network object , Network object call OnStartServer Occurs when netID.

Accept the corresponding ObjectSpawn news , Will put the corresponding object on the server netID Pass it on , Create new network objects and endow them with netID.

problem 3 NetworkIdentity Of sceneID What is it? , It's already in the scene NetworkIdentity How the object of the component contacts the server on the client side .

When network objects are not spawn Generated on the server and client , It's in the server and client scenarios themselves , We also need to establish a connection between the server and the client , This kind of object will have one sceneID To mark , This model is generally after the server scene transformation is completed ,NetworkServer call spawnObjects This kind of network object will be synchronized with all clients , When spawn After finishing , The corresponding client will generate the same netID.

problem 4 After server scenario switching , each NetworkIdentity How the object of the component contacts the client .

The order is as follows, because there are asynchronous operations , I'm not sure , The following order is only a general possible order .

  1. Server asynchronous call scenario , Send it to all clients and start switching scenarios .MsgType.Scene

  2. The client accepts MsgType.Scene, Start switching scenes .

  3. Server scenario complete , Will find all the Internet objects , then spawn These are network objects , So each network object passes through the same netID Connect .

  4. After the client scenario is completed , Call again OnClientConnect, Generally speaking , Do nothing .

problem 5 Why does the client want the permission of the network object , What can it do with authority .

Generally speaking , When spawn After a network object on a server , The server has its permissions , The client can't change the network object , In other words, after changing the corresponding properties of this network object, it cannot be synchronized to the server and other clients , It's just that changes can be seen on this machine .

So if I need to change the state of this network object , And can synchronize to all other clients , We need to have access to this network object , Because only in this way can we send Command command , To tell the server that I changed the State , The server can also tell all clients that the network object has changed its state .

Among them, local player When creating a , Current client to local player Have permission . On the client, on the network object with permission SyncVar After change , It doesn't synchronize to the server , The server is not registered at all UpdateVars news , This method still needs to be called by the client itself Command command .

problem 6 UNet What are the common package state synchronization processes , among NetworkTransform And NetworkAnimator How to communicate , If it's a network object with client permission, how can it communicate .

UNet There are two common methods of encapsulating state synchronization .

  • One is to pass. ClientRpc And Command It's encapsulating and sending messages . The client and the server call , Then the corresponding parameters are serialized , Then it goes to the server and the client to deserialize the parameter execution .

  • Second, the network built-in serialization and deserialization , The state of the serialization server , Then the client deserializes the corresponding value , Such as SyncVar Through the corresponding OnSerialize,OnDeserialize. This can only synchronize the server to the client .

These two natures are that the client and the server send each other MsgType news , The corresponding server registers the corresponding message processing with the client .NetworkAnimator Animation changes on the server , A message will be sent to all clients to inform them that the corresponding state has changed , Such as Rpc.NetworkTransform Server pass OnSerialize Serializes the corresponding value , Then the client deserializes the corresponding value .

If the client has a corresponding NetworkTransform And NetworkAnimator Permission of network objects .NetworkAnimator The corresponding client submits the status to the server , It is then distributed to all clients , Equivalent to calling Command, And in Command In the call Rpc Method .NetworkTransform The corresponding client sends messages to the server , The server updates the corresponding location , Direction . And then by deserializing to all clients .

So if the client has authorization , that NetworkAnimator And NetworkTransform Status changes on the server or authorized clients can be updated to all clients , Note that these two components are very important to localPlayerAuthority The treatment is different , stay NetworkTransform in ,localPlayerAuthority by false when , Clients cannot update to all clients , stay NetworkAnimator in ,localPlayerAuthority by true when , The server cannot update to the client .

Note that SyncVar characteristic , Even if the client is authorized , After client changes , It won't sync to another machine .

So if we design similar network components ourselves , We need to consider the corresponding processing of client authorization , It's about adding one Command command .

problem 7 Client authorization and local player What's the difference between authorization .

Generally, the permissions of objects are on the server , If you want to authorize a network object to a client , Usually by SpawnWithClientAuthority Realization , In this way, the hasAuthority by true, The corresponding playerControllerID by -1.

And local player to grant authorization localPlayerAuthority, On the corresponding network object Local Player Authority Check on , On all monitoring clients for this network object , Local player It's all about authorization true, This is generally used by players , Or the player controls the displacement of the object ,playerControllerID Greater than or equal to 0.

So client authorization is for a client , The network object on this client hasAuthority by true, And local player It's a network object , This network object on all clients localPlayerAuthority All for true.

problem 8 UNet How to realize fog map

adopt NetworkProximityChecker, In this way, each frame detects the monitoring connection of the current network object , Determine which clients need this network object . Again , If you want to achieve more complex, you can do it yourself .

problem 9 NetworkServer.Destroy What has been done

It must be a network object , And it's better to call... On the server , Invocation time , Send it to all the monitors Connect, Destroy the corresponding network object , Then the server is destroyed . Please have a look at MsgType.ObjectDestroy Message flow .

Note that in the server ,Destroy A network object , Automatically called NetworkServer.Destroy. Code in NetworkIdentity.OnDestroy.

problem 10 What did the server do when it added roles .

When the client connects to the server , After setting up automatic role creation , The role is created automatically .

1 Add a server player, Set up playercontrollerID

2 Set up current conn Of ready by true. Then detect the current conn Do you need to monitor the data on the server NetworkScene Each network object in the list of network objects , Where the isspawnFinished Express NetworkScene Whether the detection of the network object list is completed .

3 Put the server's player Of spawn down , Set the local permission client of the corresponding network object record as the current client , Corresponding playercontrollerid Send to client .

problem 11 NetworkClient And networkServer Of active What does it mean , When do you use it

networkServer After listening , Set up active by true.

networkClient After connecting to the server , Set to true.

When some messages are sent , or Rpc And Command And so on , The timing may be in the future active Before , Cause errors .

problem 12 Online Update What to do .

1 Server update , Handle things like client links and missing links , And receiving the message and finding the corresponding event processing , And serializing the data to be updated by the server network objects .

2 Client update , Processing of the above server , It is also the corresponding message processing .

3 Check whether the scenarios of server and client are loaded .

Last , Imagine , In the network environment , We pull the bow and arrow , Generative arrow , The arrow slowly opens on the client , How should we do ?

First of all, bow and arrow should be visible to all clients , We're going to build it on the server , then spawn Distribute to multiple clients , Then the current client also needs the permission of the current arrow , So that the current user can control the arrow , And the new position generated by the current user control arrow is synchronized to all clients .

Secondly, if the Valve Of LabRender Renderers , Need to shut down when starting the server , Wait until the corresponding role is loaded , Re pass localplayer Open the corresponding valveCamer, Otherwise, it's on the server valveCamer You may not get the correct shadow map .

If there is something wrong with the analysis , Welcome to point out .

Unity3D UNet More related articles about network components

  1. Android note —— Detailed explanation and summary of four components

     android The four components are activity.service.content provider.broadcast receiver. ------------------------------- ...

  2. OpenStack Detailed explanation and communication process of each component

    One .openstack origin openstack First by NASA NASA R & D Nova and Rackspace R & D swift form . Later, with apache Licensing , It aims to build public and private cloud platforms .open ...

  3. Docker Basics : Detailed explanation of network configuration

    This article will cover Docker The network function of , Including the use of port mapping mechanism to provide application services in the container to the external network , As well as through the container interconnection system to make a fast network communication between multiple containers , If you are interested, you can learn about . A large number of Internet application services include many ...

  4. OpenStack Of Swift The component,

    One : brief introduction     One . background 1. Swift It was originally made by Rackspace High availability distributed object storage service developed by the company (Object  Storage Service), And in 2010 Annual tribute to OpenSt ...

  5. OpenStack Of Trove The component,

    One : brief introduction     One . background 1.  For public cloud computing platforms , Only calculation . The three services of network and storage are not enough , In the current context of Internet applications blooming , Almost all applications use databases , And the database is often the core number of applications ...

  6. SpringCloud And its components

    SpringCloud And its components 1.Spring Cloud 1.1 Spring Cloud and Dubbo A diagram of the differences 1.2 The technology stack of microservices 2.Spring Cloud summary 2.1 Sprin ...

  7. Android in Intent The component,

    Intent It's the communication link between different components , Encapsulates the conditions for communication between different components .Intent Itself is defined as a category (Class), One Intent Objects express a purpose (Goal) Or expectations (Expectation), Syria ...

  8. use netstat Check out the network status details

    -- use netstat Check out the network status details -----------------------------2014/06/11 One .Linux Server 11 A network connection state :                     ...

  9. Linux Detailed explanation of network configuration file

    --Linux Detailed explanation of network configuration file ----------------------2013/10/03 Currently in the enterprise server Linux In the system ,RHEL Have an absolute advantage , Whether it has been tested in Internet companies or now Vir ...

Random recommendation

  1. poj 1112

    Last night . Tell the truth , I can see at a glance that it's a bipartite graph , It's a bipartite graph +dp(01 knapsack ). But the tragedy is that I can see at a glance that the algorithm is correct , But I always thought it was wrong , Wasted a long time, like other algorithms (TAT). Today, I've finally replaced him ...

  2. Java Solutions to upload truncation vulnerabilities

    Solution of file upload vulnerability 1. Most effective , Set the file upload directory directly as non executable , about Linux for , To undo the contents of 'x' jurisdiction : In fact, many upload applications of large websites will be placed on independent storage as static files , First, it is convenient to use cache ...

  3. oracle Data type details --- Date type ( Reprint )

    oracle Data type details --- Date type oracle The data type looks very simple , But when you use it, you will find that there are many knowledge points , This article is about me ORACLE Some collation of date data types , It's all about developing introductory materials , Share with you : notes : because INTER ...

  4. SQLSERVER Remote backup 、 recovery ( turn )

    SQLSERVER Service instance name :192.168.0.2 The name of the database to be backed up : a Backup machine name (Client End ):192.168.0.3 Backup user :zf password :123 Backup machine domain name :domain Backup machine provides backup ...

  5. java Image file transmission and display in (Socket as well as ServerSocket demonstration )

    // Client part package testSix; import java.awt.Graphics; import java.io.IOException; import java.io.InputS ...

  6. RFS_oracle The operation of

    1. cx_Oracle Python  Connect Oracle  database , Need to use cx_Oracle  package . The download address of the package :http://cx-Oracle.sourceforge.net/ When downloading , Be careful ...

  7. 【 Reprint 】 Color space -RGB、HSI、HSV、YUV、YCbCr An introduction to the

    Reprinted from yuanjiahui's blog . Color is usually described by three relatively independent attributes , Three independent variables work together , Nature forms a spatial coordinate , This is the color space . And colors can come from different angles , Describe it in groups of three different attributes , There's a different color space . but ...

  8. C#.Net operation XML Method 2

    The blog above , In the blog above, it's through System.Xml Class in the XML File creation . Delete and change operations . Next, we will introduce another method , In the whole process of operation , It's just a new class , It's no big deal . D ...

  9. git Video tutorial

    git Compact video tutorial -2 Hourly quick introduction , The little tutorial will be finished soon . Wang Wang QQ:Git It is the most advanced distributed version control system in the world ( Not one of them. ). Git There is a very high pressure , In a nutshell : marvelous,gorgeous,splendid and posh . such ...

  10. Micropython Example of TPYBoard Caller ID function demonstration

    One .TPYBoardV702 Introduce TPYBoardV702 It's the only one on the market that supports the communication function MicroPython Development board : Support Python3.0 And above versions run directly . Support GPS+ Beidou dual mode communication .GPRS through ...