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?
-
read this first: https://stackoverflow.com/a/54184457/294884 – Fattie Jan 14 '19 at 15:51
3 Answers
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!

- 10,263
- 4
- 40
- 56
-
It is quite old question but since I ventured here and any of above links didnt work for me, here is what I have found helpful 1. [good article](http://www.albahari.com/threading/); and 2. [job queue example](http://wiki.unity3d.com/index.php/JobQueue) from Unity Wiki – FullStackForger May 12 '17 at 02:54
-
-
1I'd also suggest taking a look at [this article](https://www.pluralsight.com/guides/using-task-run-async-await) to better understand the difference between I/O-Bound (e.g. reading a file) and CPU-Bound operations. Then, try to adopt the async/await pattern in Unity3D following [these guidelines](https://www.youtube.com/watch?v=7eKi6NKri6I). – fibriZo raZiel Jan 26 '21 at 11:59
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.

- 90
- 6
-
2This is correct. You can do threading in Unity as long as the class does not inherit from MonoBehaviour. – Esa Mar 03 '14 at 13:08
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

- 15,894
- 22
- 55
- 66
-
1Coroutines are not actual threads. Only the e.g the WWW-functionality is truly threaded. – Esa Mar 03 '14 at 13:07
-