Use Unity API from another Thread or call a function in the main Thread

前端 未结 4 1451
醉梦人生
醉梦人生 2020-11-21 22:19

My problem is I try to use Unity socket to implement something. Each time, when I get a new message I need to update it to the updattext (it is a Unity Text). However, When

4条回答
  •  醉梦人生
    2020-11-21 23:02

    Use UniRx's multithreading pattern, UniTask and RxSocket together.

    [SerializeField] private Text m_Text;
    
    async UniTaskVoid Connect() {
        IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 12345);
    
        // Create a socket client by connecting to the server at the IPEndPoint.
        // See the UniRx Async tooling to use await 
        IRxSocketClient client = await endPoint.ConnectRxSocketClientAsync();
    
        client.ReceiveObservable
            .ToStrings()
            .ObserveOnMainThread()
            .Subscribe(onNext: message =>
        {
            m_Text.text = message;
        }).AddTo(this);
    
        // Send a message to the server.
        client.Send("Hello!".ToByteArray());
    }
    

提交回复
热议问题