0

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;
});
1
  • Does print(data["id"]) work? If not, what do you get when you do print(data.toString())? Commented Jul 27, 2017 at 14:42

1 Answer 1

0

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']);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.