Unity3d(C#)错误提示:禁止在线程中进行游戏对象比较!

今天刚刚写完异步Socket客户端的数据收发,在进行测试的时候,Unity报出错误:

 

CompareBaseObjectsInternal can only be called from the main thread.


详情如下:

ERROR : 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.


 

在Unity3d官方论坛有网友请教了这个问题

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


答案如下:

Seems like you must be calling Unity specific functions from another thread, compare gameobjects means you are checking if one gameobject equals another, apparently this is not threadsafe, so you would need to make sure your separate thread does NOT interract with Unity functions at all. 

 

翻译过来就是说:

在Unity中需要遵循C#的线程安全,不能在另外的线程对Unity的GameObject进行相等比较操作。

 

在我的工程中,当Socket BeginConnect的时候就会 调用WindowManager来显示一个等待界面

当Connect Success或者failed的时候,就会关闭。

 

显示界面是在Unity线程中执行

关闭界面是在Socket的异步回调中执行

 

从Mono的断点来看这两个不是同一个线程。

Unity3d(C#)错误提示:禁止在线程中进行游戏对象比较!_第1张图片

 

Unity3d(C#)错误提示:禁止在线程中进行游戏对象比较!_第2张图片

 

 

因为在Wait.GetSingleton().Close() 中有用到WindowManager.GetSingleton()

如下:

	public static CCWindowManager GetSingleton()
	{
		if(m_sInstance==null)
		{
			//Helper.LogError("CCWindowManager m_sInstance==nul");
			GameObject obj = new GameObject("CCWindowManager");
			m_sInstance=obj.AddComponent();
		}
		return m_sInstance;
	}


 

所以在判断 m_sInstance == null 的时候出现了错误。

 

解决方法:

将关闭等待界面的代码移到了Update中。

 

 

你可能感兴趣的:(Unity,unity,线程安全,线程,异步,socket)