使用來(lái)自其他線程的統(tǒng)一API或調(diào)用主線程中的函數(shù)我的問(wèn)題是,我試圖使用UnitySocket來(lái)實(shí)現(xiàn)一些東西。每次,當(dāng)我收到一條新消息時(shí),我需要將它更新為更新文本(它是一個(gè)統(tǒng)一文本)。但是,當(dāng)我執(zhí)行以下代碼時(shí),無(wú)效更新并不是每次都調(diào)用。我不包括updatetext.GetComponent<Text>().text = "From server: "+tempMesg;在voidgetInformation中,這個(gè)函數(shù)在線程中,當(dāng)我在getInformation()中包含這個(gè)函數(shù)時(shí),它會(huì)出現(xiàn)一個(gè)錯(cuò)誤:getcomponentfastpath can only be called from the main thread我想問(wèn)題是我不知道如何在C#中一起運(yùn)行主線程和子線程?或許還有其他問(wèn)題.。希望有人能幫忙.。這是我的密碼: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貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
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 關(guān)注
- 1442 瀏覽
添加回答
舉報(bào)
0/150
提交
取消