Unity3d报告奇怪的错误CompareBaseObjectsInternal can only be called from the main thread.

其中使用了该项目.NET的Async Socket代码。后来不知道什么时候这个奇怪的错误的出现:

CompareBaseObjectsInternal can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

怪异是由于报错并没有影响程序运行,而是正确地接收了server返回的信息,而且通过回调正确显示出来。说明回调被运行了。可是从回调再调用一个解析器却一直不运行。是不是上面的错误导致的?

搜索百度CompareBaseObjectsInternal关键词仅仅有8个结果,http://blog.csdn.net/jixuguo/article/details/26693977相对有些意义,可是博文为转载。后来看到原文,大致的意思是假设从子线程调用主线程的callback。须要给回调加一个interface。

这个和我的情况不太一样,參考意义不大。

然后google。非常不幸古大哥一直载入载入。

。。

于是去yahoo,竟然还没有抽筋。

最前面搜索出来的几篇文章就是unity论坛上的。大致看出一些眉目。

http://forum.unity3d.com/threads/comparebaseobjectsinternal-error.184069/#post-1258700

 

http://forum.unity3d.com/threads/comparebaseobjectsinternal-can-only-be-called-from-the-main-thread-annoying.195902/http://forum.unity3d.com/threads/comparebaseobjectsinternal-can-only-be-called-from-the-main-thread-annoying.195902/

 

http://community.kii.com/t/error-comparebaseobjectsinternal-can-only-be-called-from-the-main-thread/378#!

 

http://answers.unity3d.com/questions/704284/comparebaseobjectsinternal-can-only-be-called-from-1.html

分析出来我的问题大概是在主线程里面注冊了回调,

        //注冊全部事件的响应代码
        NetEventManager.GetInstance().netMessageReceived_event += OnNetMessageReceived;
        NetEventManager.GetInstance().gateServerConnected_event += OnGateServerConnected;
        NetEventManager.GetInstance().errorMessageOccured_event += OnErrorReceived;

然后socketclient对象是异步的,所以做了多线程处理,当socketclient接收到消息时,回调了主线程的函数(继承自monobehaviour),这时候就导致了报错。上面第一篇unity论坛博文解释得比較清楚,大概就是unity对于API调用主线程做了限制:

“Unity chose to limit API calls to main-thread, to make a simple and solid threading model that everyone can understand and use.”

依据这个解释,我把上面的代码凝视掉。程序就不报错了。

预计这些事件响应代码要放到非monobehavior的类里面去。就能够避免上面说的线程安全问题。

 

因为我感兴趣的多线程编程的基本或白色,上面的解释是正确的、有没有更好的解决办法。也希望你有种。

版权声明:本文博主原创文章。博客,未经同意不得转载。

posted on 2015-09-22 20:43  gcczhongduan  阅读(1687)  评论(0编辑  收藏  举报