Search Unity

Question Is there an example on sending structured data with Transport?

Discussion in 'Unity Transport' started by CptanPanic, Feb 8, 2023.

  1. CptanPanic

    CptanPanic

    Joined:
    Dec 19, 2022
    Posts:
    15
    I have setup the Server/Client example with Transport that sends a single number. Now I want to send more complex data like a structure that has multiple fields. I am assuming that I would have to set the data of the structure, and then serialize it, and use WriteBytes() to send, but this is just a guess. Are there any examples of something like this? If not, could you just give me the outline on how to do this?
    Thanks.
     
  2. simon-lemay-unity

    simon-lemay-unity

    Unity Technologies

    Joined:
    Jul 19, 2021
    Posts:
    441
    Your assumption is basically correct. In general the transport package is rather un-opiniated about how serialization is performed. The idea is to leave as much flexibility as possible to users in case you want to use things like protocol buffers or other such serialization frameworks.

    If you don't already have a serialization solution that you want to use, the transport does provide some basic functionality in
    DataStreamWriter
    . As you've seen in the documentation, it can serialize basic types like numbers and fixed strings. There are also packed versions of these methods which can be useful to save bandwidth.

    For an example of how these basic primitives can be assembled to provide serialization of more complex data types, you can look at how they're used in Netcode for Entities. Here's an example from their documentation of how to implement serialization of custom RPC data. Basically the idea is that you'd have some
    ISerializer
    interface with
    Serialize
    and
    Deserialize
    methods. Each structure/class you want to send over the network can then implement this interface using the basic building blocks provided by
    DataStreamWriter
    /
    DataStreamReader
    .