unity-game-enginesocket.iojson.netunityscript

how can i make a callback function on Unity JS


I've decided to make a game with Unity + Node.js, and I'm trying to use a socket.io library with unityscript

Here is my code so far:

#pragma strict

import System.Collections.Generic;
import UnityEngine.UI;
import Quobject.SocketIoClientDotNet.Client;

public class SocketIOScript extends MonoBehaviour {

    var _socket : Socket;

    function Start () {
        if(!_socket) {
            _socket = IO.Socket("http://localhost:3000");
            _socket.On("connect", function(asd) {
                _socket.Emit("chat", "hello");
            });
            _socket.On("chat", function(data) {
                print(data.id);
            });
        }
    }
}

but this line

_socket.On("chat", function(data) {
    print(data.id);
});

gives an error:

Assets/SocketIOScript.js(24,52): BCE0019: 'id' is not a member of 'Object'.

When I tried to see what is the type of "data":

print(typeof data);

it says:

Newtonsoft.Json.Linq.JObject

I don't know what to do. It took my whole yesterday, so I decided to ask here.

Here is a C# version of what I'm trying to accomplish (from the socket.io-unity demo)

socket.On ("chat", (data) => {
    string str = data.ToString();

    ChatData chat = JsonConvert.DeserializeObject<ChatData> (str);
    string strChatLog = "user#" + chat.id + ": " + chat.msg;
});

Solution

  • I've realized that callback functions are same as javascript

    and solved the problem by adding

    import SimpleJSON;
    

    and then

    _socket.On("chat", function(param) {
    
        var data = JSON.Parse(param.ToString());
    
        print(data['id']);
        print(data['msg']);