How to execute async task in Unity3D?

2019-01-22 22:04发布

Does any body know any way of doing async task in unity. I am looking for that for a while but couldn't find any way to do, yet. I am trying to do a coloring game, there is a flood fill algorithm that takes some time to process. Thanks for any help.

5条回答
beautiful°
2楼-- · 2019-01-22 22:08

use a CoRoutine you can set them going, and execute a little part of it each frame to time-slice your code. co routines

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-22 22:09

You could just use C# threads to make your async work. You can find out more about threads over here.

You must note that you cannot interact with Unity from the working thread, so after finishing the work you must use the results from within Unity thread. You can do this by simply setting a flag on the MonoBehaviour that will do the update and check the flag in the Update method. Something similar to this:

void Update()
{
  if( _workDone )
  {
   ...display it
  }
}
查看更多
放我归山
4楼-- · 2019-01-22 22:24

I know this question is old, but it is still quite relevant. I have coded my own solution in my open source framework. If you are interested, you can find all the info here:

http://www.sebaslab.com/svelto-taskrunner-run-serial-and-parallel-asynchronous-tasks-in-unity3d/

It supports multithreading as well.

查看更多
叼着烟拽天下
5楼-- · 2019-01-22 22:28

You can now directly use async await with Task in Unity 2017. More detail here

查看更多
爷、活的狠高调
6楼-- · 2019-01-22 22:34

You can use threads in Unity to execute your async taks. Usually you run detached threads (from the Unity UI) to do long running processes and check on results (you can't interact with Unity from the working thread). The common approach is to use a class which represents a threading job which will be initialized by the Unity main thread. Then you start a worker thread on a function of that class and let it do it's job (Coroutines run on the Unity main thread so are not real threads. Best article on Coroutines is here)

Here's an example of the approach described above (see accepted answer):

http://answers.unity3d.com/questions/357033/unity3d-and-c-coroutines-vs-threading.html

You might also want to try a UnityGems package that achieves the same effect but provides convenience (such as closure support):

http://unitygems.com/threads/

HTH. Best!

查看更多
登录 后发表回答