how to use c# threads in unity3d for android platf

2019-04-10 10:20发布

问题:

I am in need to load files, scenes and play animations in threads.. Tried loading files via www in Android... how to do other stuff via threads? But how come a game engine doesn't allow us to create threads? or my understanding is wrong? how can one create threads in UNITY3D?

回答1:

You can use threads in Unity but the engine is not thread safe. Usually you run detached threads (from the Unity UI) to do long running processes and check on results (you cannot 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). See this page

HTH. Best!



回答2:

From my own personal experience with Unity, you cannot create/run a separate thread unless the thread doesn't use any of Unity's api. So that means no gameObjects or things of similar nature.I've successfully done it myself for my own pathfinding so I know it is possible. Good Luck! I hope this helps.



回答3:

A commonly used approarch in Unity3D is to use Coroutines.

IEnumerator DoSth()
{
    ...
    yield retrun ... ;       
}

To call/Consume the coroutine:

StartCoroutine(DoSth());  // OK
StartCoroutine("DoSth");  // Also fine
StopCoroutine("DoSth");   // You can stop it as well