为了账号安全,请及时绑定邮箱和手机立即绑定

使用来自其他线程的统一API或调用主线程中的函数

使用来自其他线程的统一API或调用主线程中的函数

泛舟湖上清波郎朗 2019-06-10 16:43:01
使用来自其他线程的统一API或调用主线程中的函数我的问题是,我试图使用UnitySocket来实现一些东西。每次,当我收到一条新消息时,我需要将它更新为更新文本(它是一个统一文本)。但是,当我执行以下代码时,无效更新并不是每次都调用。我不包括updatetext.GetComponent<Text>().text = "From server: "+tempMesg;在voidgetInformation中,这个函数在线程中,当我在getInformation()中包含这个函数时,它会出现一个错误:getcomponentfastpath can only be called from the main thread我想问题是我不知道如何在C#中一起运行主线程和子线程?或许还有其他问题.。希望有人能帮忙.。这是我的密码:using UnityEngine;using System.Collections;using System;using System.Net.Sockets;using System.Text;using System.Threading;using UnityEngine. UI;public class Client : MonoBehaviour {     System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();     private Thread oThread;//  for UI update     public GameObject updatetext;     String tempMesg = "Waiting...";     // Use this for initialization     void Start () {         updatetext.GetComponent<Text>().text = "Waiting...";         clientSocket.Connect("10.132.198.29", 8888);         oThread = new Thread (new ThreadStart (getInformation));         oThread.Start ();         Debug.Log ("Running the client");     }     // Update is called once per frame     void Update () {         updatetext.GetComponent<Text>().text = "From server: "+tempMesg;         Debug.Log (tempMesg);     }     void getInformation(){         while (true) {             try {                 NetworkStream networkStream = clientSocket.GetStream ();                 byte[] bytesFrom = new byte[10025];                 networkStream.Read (bytesFrom, 0, (int)bytesFrom.Length);                 string dataFromClient = System.Text.Encoding.ASCII.GetString (bytesFrom);                 dataFromClient = dataFromClient.Substring (0, dataFromClient.IndexOf ("$"));                 Debug.Log (" >> Data from Server - " + dataFromClient);                 tempMesg = dataFromClient;                 string serverResponse = "Last Message from Server" + dataFromClient;
查看完整描述

3 回答

?
慕慕森

TA贡献1856条经验 获得超17个赞

我一直在用这个解决方案来解决这个问题。使用此代码创建脚本,并将其附加到“游戏”对象:

using System;using System.Collections.Generic;using System.Collections.Concurrent;using UnityEngine;public class ExecuteOnMainThread :
 MonoBehaviour {

    public readonly static ConcurrentQueue<Action> RunOnMainThread = new ConcurrentQueue<Action>();

    void Update()
    {
        if(!RunOnMainThread.IsEmpty())
        {
           while(RunOnMainThread.TryDequeue(out action))
           {
             action.Invoke();
           }
        }
    }}

然后,当您需要调用主线程上的某个内容并从应用程序中的任何其他函数访问UnityAPI时:

ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {

    // Code here will be called in the main thread...});


查看完整回答
反对 回复 2019-06-10
  • 3 回答
  • 0 关注
  • 1278 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信