GitHub Documentation Patreon donate button

Unity3d Send Data through Component

  • Hi there,

    i am using Unity3D for client and i have realy big trouble with sending data throught some Components.
    For example in the scene root i have ColyseusClient object with script where i am creating room etc (like in example).

    Then i have Player gameobject with some component e.q. SendMovePosition Component.

    1. How to send message through this SendMovePosition Component (how to use Colyseus Room there)?
      I cant make Room instance static inside ColyseusClient.
    2. How to pack data to json via Unity3d? Right now i had this idea to pack this manualy like
    (string.Format(@"{""test"":""value"", ""x"": ""{0}"", ""y"": ""{1}""}", hit.point.x, hit.point.z));

    but is there any other (build-in) option?

    Hope you will help me because i really want to understand this!

  • administrator

    @halome you usually won't bother about serializing the data.

    You can send the raw data to the room like this:

    // Client-side
    room.Send(new { command = "move", x = 1, y = 2 });

    From the server-side, inside the onMessage, you can use the command to update your room state.

    // Server-side
    // ...
    onMessage (client, data) {
        if (data.command == "move") {
            console.log("let's move to", data.x, data.y);
            // TODO: update this.state using data.x / data.y
    // ...

    You can listen to any attribute change in the state of the server from the client-side through room.Listen("path/to/your/attribute", this.YourChangeCallback).

    The mindset is usually like this:

    • Client send a message to the server, as a request to update the state
    • State is updated inside onMessage callback
    • The updated attributes in the state arrive to all connected clients in the next patch tick
    • The client applies the change via room.Listen (which contains the single attribute changed) or room.OnUpdate (which contains the whole state from the server)

    Hope this helps,


GitHub Documentation Patreon donate button

© 2020 Endel Dreyer