亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用來自其他線程的統一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 關注
  • 1449 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號