Search Unity

Bug Any sort of JSON deserializing stops code completely

Discussion in 'Scripting' started by Minespeed1009, Mar 6, 2023.

  1. Minespeed1009

    Minespeed1009

    Joined:
    Apr 16, 2019
    Posts:
    7
    Code (CSharp):
    1. private void Start()
    2.         {
    3.             ws = new WebSocket("ws://localhost:8080");
    4.             ws.Connect();
    5.             ws.OnMessage += (sender, e) =>
    6.             {
    7.                 var data = e.Data;
    8.                 Debug.Log($"Packet received: {data}");
    9.                 object json = JsonConvert.DeserializeObject(data);
    10.                 Debug.Log("test");
    11.                 Debug.Log(json);
    12.             };
    13.         }
    This is connecting to my Node.JS websocket server. Whenever I press space, the game sends a test packet to the server, and the server should respond with a packet like
    {"type":"setPos","pos":{"x":0,"y":0,"z":0}}
    , and Unity logs that. However, it never logs "test". As a matter of fact, any code I put past the JsonConvert never runs. I also tried using JsonUtility, but that doesn't work either. Please help!
     
    Last edited: Mar 7, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    Photographs of code are not a thing. If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    Everything you're doing above will potentially block the main thread.

    Networking in Unity is always best accomplished with UnityWebRequest(). Other options may not be fully supported.

    Whenever you're debugging networking, start here:

    Networking, UnityWebRequest, WWW, Postman, curl, WebAPI, etc:

    https://forum.unity.com/threads/using-unity-for-subscription-lists.1070663/#post-6910289

    https://forum.unity.com/threads/unity-web-request-acting-stupid.1096396/#post-7060150

    And setting up a proxy can be very helpful too, in order to compare traffic:

    https://support.unity.com/hc/en-us/articles/115002917683-Using-Charles-Proxy-with-Unity

    Problems with Unity "tiny lite" built-in JSON:

    In general I highly suggest staying away from Unity's JSON "tiny lite" package. It's really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

    Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window -> Package Manager).

    https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

    Also, always be sure to leverage sites like:

    https://jsonlint.com
    https://json2csharp.com
    https://csharp2json.io