- Home /
Data Synchronization using OnSerializeNetworkView
Unity suggests:
int health = 0;
if (stream.isWriting)
{
health = Health;
stream.Serialize(ref health);
}
else
{
stream.Serialize(ref health);
Health = health;
}
Works the same way (so far):
stream.Serialize(ref Health);
So which is better? Does it matter if I am writing or reading?
Answer by Graphicated · Apr 07, 2012 at 07:02 AM
sure it matters, and it depend on what you are willing to do...
when you go deeply in Networking, and face different situations, you will be thanksfull to have such methods,, for example, what if only the owner is allowed to execute on server ? .. is anyone allowed to move things in the game as they like ?
what kind of functions should reach all players ? and which should be executed only on a specific players machine?
so in this case, when you ask if(stream.isWriting) .. you are asking unity to check if the newtworkview owner is writing now so it can send data ,otherwise the player will only be able to recieve data.. now here, each player is owner of his charachter lets say and has his own networkview.
well this will not help you for a long time, because if each user has his own Networkview this might gets you in trouble later..
and this way you can limit the movement or execution of movment to the server owner only ! here is an example about movement :
function Update(){
if(Network.isServer){
//Only the server can move the cube!
var moveDirection : Vector3 = new Vector3(-1*Input.GetAxis("Vertical"), 0,Input.GetAxis("Horizontal"));
var speed : float = 5;
transform.Translate(speed * moveDirection * Time.deltaTime);
}
}
function OnSerializeNetworkView(stream : BitStream, info : NetworkMessageInfo)
{
if (stream.isWriting){
//Executed on the owner of the networkview; in this case the Server
//The server sends it's position over the network
var pos : Vector3 = transform.position;
stream.Serialize(pos);//"Encode" it, and send it
}else{
//Executed on the others; in this case the Clients
//The clients receive a position and set the object to it
var posReceive : Vector3 = Vector3.zero;
stream.Serialize(posReceive); //"Decode" it and receive it
transform.position = posReceive;
}
you better concider the Authorative way ,, where players sends data to server, so server then decides what to do and sends data depending on that. and not to send direct data from player to player.. take a look at "RPC calls" in unity also.