Unity3d 从线程访问游戏对象:内部获取游戏对象错误

本文关键字:对象 游戏 内部 获取 错误 访问 Unity3d 线程 | 更新日期: 2023-09-27 18:33:06

我正在使用自定义TCP套接字客户端类连接到服务器。当服务器响应特定消息/命令时,我想更改活动菜单,但 Unity3D 告诉我无法从其他线程但主线程访问游戏对象。

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

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

Unity3d 从线程访问游戏对象:内部获取游戏对象错误

这是因为您无法从其他线程访问游戏对象。您可以在主线程中实现侦听器:

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
    }