Unity3d从线程访问GameObject:InternalGetGameObject错误

时间:2014-12-04 20:26:49

标签: c# user-interface tcp unity3d

我使用自定义TCP套接字客户端类连接到服务器。当服务器响应特定的消息/命令时,我想更改活动菜单,但是Unity3D告诉我从其他线程访问GameObjects但主线程是不可能的。

目前我正在使用一个使用blockin IO的接收线程。我尝试使用BeginReceive接收消息并等待特定命令然后更改活动菜单,但它给了我同样恼人的错误。

有没有一种简单而好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:2)

这是因为您无法从其他线程访问GameObjects。您可以在主线程中实现一个侦听器:

void Start(){
    StartCoroutine(CheckOtherThreadsEveryFrame());
    StartCoroutine(CheckOtherThreadsOnceASecond());
}

IEnumerator CheckOtherThreadsEveryFrame(){
    while(true){
        //check if another thread has put some data where this method can see 
        yield return null; //wait until next frame      
    }
}
IEnumerator CheckOtherThreadsOnceASecond(){     
    while(true){            
        //check if another thread has put some data where this method can see           
        yield return new WaitForSeconds(1); //wait for 1 second
    }