Unity线程安全:CompareBaseObjectsInternal can only be called from the main thread

本文介绍了Unity中解决多线程调用主线程时遇到的线程安全问题的方法。通过实例展示了如何避免在子线程中直接调用Unity组件,而是通过收集数据并在主线程的Update函数中进行处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在unity中我们使用多线程时。用子线程调用主线程时。用到unity的东西时就会报如下的错误。

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.

一个简单的办法就是。当多线程调用时。将内容展示存下来。然后通过主线程的函数去下发。比如Update下发

例:

public void BeginTheTimer()
{
	//建立连接
	try
	{
		socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		socketClient.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9070));
		IsConnected = true;
	}
	catch (Exception e)
	{ 
		Debug.Log(e);
	}
	
	Thread receiveThread = new Thread(new ThreadStart(socketReceive));
	receiveThread.Start();
	receiveThread.IsBackground = true;
}
 
//数据接收线程添加变量DateTime lastConnect=DateTime.now;
//若接收数据为echo,则不作处理,若为其他数据,显示在richTextBox中;
public void socketReceive()
{
	while (true)
	{
		try
		{
			byte[] buff = new byte[1024];
			int count = socketClient.Receive(buff);
			if (count > 0)
			{
				string str = Encoding.UTF8.GetString(bytes, 0, i);
                message(str);
			}
		}
		catch (SocketException)
		{
			IsConnected = false;
			Thread.CurrentThread.Abort();
		}
	}
}
private void message(string data)
{
	notifierDataList.Add(data);
}
 
void Update()
{
	if(notifierDataList.Count > 0)
	{
		//如这。我用的是接口下发消息。通过字典来队列消息。每次下发一条。然后将已下发的移除
		//就不会出现线程安全问题了
		Notifier(999, null, notifierDataList[0]);
		notifierDataList.RemoveAt(0);
	}
}

  转载来源:小宝个人笔记 » Unity线程安全:CompareBaseObjectsInternal can only be called from the main thread

转载于:https://www.cnblogs.com/UnrealEra/p/6141118.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值