Unity中的线程安全 [英] Thread safety in Unity

查看:129
本文介绍了Unity中的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Unity中,线程无法操作UnityEngine提供的对象,如transform.position等,这导致了一个异常,即只能从主线程调用get_transform. 但是,这些方法可以在像BeginReceive这样的异步函数中使用,所以有人可以告诉我为什么吗?异步功能不是线程还是其他?

In Unity, the thread cannot operate the object provided by UnityEngine like transform.position etc, which caused an exception that get_transform can only be called from the main thread. However, these methods can be used in some async function like BeginReceive, so is there anyone can tell me why? The async function is not thread or sth else?

我尝试下面的代码:

void Start(){
    AsyncCallback callback = new AsyncCallback (demo);
    callback.BeginInvoke (null, null, null);
}

void demo(IAsyncResult result){
    Debug.Log(Thread.CurrentThread.ManagedThreadId);
    Debug.Log(gb.transform.position.ToString());
}

当我在Unity Editor上运行代码时,它确实引发异常.但是,当我直接在Android手机上运行此代码时,它没有引发任何异常,并且代码已正确执行.

It does throw an exception when I run the code on Unity Editor. However, when I run this code on an Android phone directly, it didn't throw any exception and the code was performed correctly.

applogcat中的日志显示:

The log in applogcat shows that:

Line 13497: 02-20 14:37:49.973 31027 31697 I Unity   : 3
Line 13501: 02-20 14:37:49.975 31027 31697 I Unity   : (0.0, 0.0, 0.0)

因此,该函数似乎在另一个线程而不是主线程上运行,所以有人可以告诉我为什么在这种情况下进行转换吗?

So it seems that the function runs on another thread instead of main thread, so could anyone tell me why transform works on this situation?

推荐答案

不允许从与UI线程不同的线程中调用UI API.

UI APIs aren't allowed to be called from a different thread than the UI one.

这简化了Unity在幕后的工作方式,并使其实际运行速度更快.

This simplifies how Unity works behind the scenes and actually makes it faster.

一些异步方法是使用事件循环而不是不同的线程调度的.仅仅因为方法是异步的,并不意味着它可以在不同的线程上运行.

Some async methods are dispatched using an event loop and not a different thread. Just because a method is async it doesn't mean it gets to run on a different thread.

在Unity中最明显的例子就是协程.它们确实运行异步,但是在主线程上.这是可能的,因为Unity将所有内容添加到列表中并在每一帧执行它们.

The most obvious example of this in Unity are Coroutines. They do run async, but on the main thread. This is possible because Unity adds all of to a list and executes them every frame.

这篇关于Unity中的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆