Sending structs over network (NetworkTransport API)


I am developing a multiplayer game on top of the Low Level API (NetworkTransport API).
I’m at the point where I want to send different information, structured in different structs. (e.g. SpawnInformation, PositionUpdate and so on)

So my idea is to convert the struct to a byte array, send the array and convert it back.
But here is the problem. How does the receiver know what type of struct that is?
One thing I noticed is that if I add a type byte at the start i can use this to cast it to different objects.

But I am interested in your ideas, since this is probably a pretty common task for network developing.


Of course you need to serialize the type of the struct in some way. Generally structs are a bad choice when the data should be serialized / deserialized because of their valuetype nature.

Also you usually don’t want to just send the plain information but usually “messages”. Well, that’s what the HighLevelAPI actually does for you.

So if you want to roll your own, you have to define your own message format. A message usually contains a message type and often a variable amount of payload data. There are examples in the docs. Keep in mind that a packet is limited to the configured “MaxPacketSize”. So larger data streams need to be split into several packets.

When dealing with binary streaming data the best solution is to use a BinaryReader with a MemoryStream. That way you can simply read your message component by component. I haven’t use Unity’s NetworkReader yet, but even they claim it’s part of the high level API, it looks like it’s just a standalone stream helper just like the BinaryReader but has support for most Unity types.