- Home /
OnSerializeNetworkView multiple variables
I'm wanting to send more than one variable back and forth across the same network, but right now I have only one script that manages those variables. Am I going to need to write an entirely new script and assign a NetworkView for every single variable I want to send back and forth?
Answer by ThibaultD · Jul 19, 2012 at 03:05 AM
You can send several variables in OnSerializeNetworkView(), like so (C#):
stream.Serialize(ref aVariable);
stream.Serialize(ref anotherVariable);
for (int i = 0; i < positions.Length; i++)
{
stream.Serialize(ref positions[i]);
}
...
Exactly. The important thing is that you deserialize the exact same amount and types of variables you have serialized. If the size of positions can change, you should serialize the positions length before you serialize the elements. That way the receiving side can reconstruct the array, no matter how many elements.
I see how you send them, do you need to receive them in any order or does unity sort them out. If it's a bit stream and if I send 4 Vector3s, how does unity know what data goes where?
The same method is called to send and to receive. The objects passed as reference are automatically serialized and deserialized depending on the case. You can also use "stream.isReading" and "stream.isWriting" to distinguish the two cases.
As to how Unity knows how to split the data, I don't know but I guess all the serialized objects are packed between a header and footer that identifies this specific packet for this specific script. The important thing, like Bunny83 said, is that you should serialize/deserialize the same number and type of data, and in the same order, on writing and reading.