jirihybek / unity-websocket-webgl

Hybrid WebSocket implementation for Unity 3D with support of native and browser client.
Other
248 stars 61 forks source link

TextMeshPro not updated when using Websocket's callback? #5

Closed kokizzu closed 5 years ago

kokizzu commented 5 years ago

I'm using Unity 2018.2, it's weird to see that the property on editor is correct but textmeshpro not updated only when using websocket's callback (normal event works, ain't working only when using websocket's callback)

minimum code to reproduce

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using HybridWebSocket;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Main : MonoBehaviour 
{

    public Button sendButton;
    public TextMeshProUGUI chatLabel;
    public TMP_InputField chatInput;

    WebSocket ws;

    void Start()
    {
        ws = WebSocketFactory.CreateInstance("ws://echo.websocket.org");
        ws.OnOpen += websocket_Opened;
        ws.OnError += websocket_Error;
        ws.OnClose += websocket_Closed;
        ws.OnMessage += websocket_MessageReceived;
        ws.Connect();

        sendButton.onClick.AddListener(delegate ()
        {
            AppendText("sending: " + chatInput.text);
            ws.Send(Encoding.UTF8.GetBytes(chatInput.text));
        });
    }

    private void websocket_Error(string errormsg)
    {
        throw new NotImplementedException();
    }

    private void websocket_MessageReceived(byte[] data)
    {
        AppendText("from server: " + Encoding.UTF8.GetString(data));
    }

    private void websocket_Closed(WebSocketCloseCode closeCode)
    {
        AppendText("Websocket closed: " + closeCode);
    }

    private void websocket_Error(object sender, EventArgs e)
    {
        AppendText("Websocket error: " + e);
    }

    private void AppendText(string str)
    {
        Debug.Log(str);
        chatLabel.text += str + "\n";
    }

    private void websocket_Opened()
    {
        AppendText("Websocket opened.. ");
    }
}
CodeSpartan commented 5 years ago

This is correct behavior, not a bug. OnMessage runs on a different thread. You can't access anything from Unity's main thread from it. You have to leave received information somewhere in static fields for the main thread to find.

kokizzu commented 5 years ago

Ah nice, thanks, links for reference: https://stackoverflow.com/a/25271152/1620210