使用来自其他线程的统一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(); } } }}
ExecuteOnMainThread.RunOnMainThread.Enqueue(() => { // Code here will be called in the main thread...});
- 3 回答
- 0 关注
- 1370 浏览
添加回答
举报
0/150
提交
取消