We are considering trying out Unity, and I am doing some research on the available functionality so we can make a decision.
From what I can find when doing a Google search, Unity does not support multi-threading, however most of the information I found was prior to Unity 3D, and now I see that version 4 is about to be released any moment.
So I am wondering if something has changed in this regard?
Do anyone know if Unity 4 support multi-threading and possibly even parallelization (parallel programming)?
To any knowledge we got so far there will be no difference in how threading works.
Its important to keep in mind that .NET threading assumes you to be on a managed application where .NET has control over it.
But in case of Unity thats not how it works at all.
The scripting you do runs within a VM controlled by native code (the Unity engine) into which and out of which calls are under tight control by the engine, as such threading into that native layer (the Unity API) is likely never going to happen at least not through .NET threading support. if it happens then likely more in a ‘tasklet alike’ API where the Unity Engine remains under control of the accesses, otherwise its not gonna work out.
But nothing prevents you from using Threading to offload calculations etc and then feed them back through standard threadsafe approaches like static System.Collections / System.Collections.Generic queues to handle them in Update, LateUpdate, FixedUpdate within a monobehaviour.
Unity supports multithreading. It’s already multi-threaded itself, though I don’t think it’s re-entrant. You are free to create your own threads though - here’s a sample component that basically just sits there and spins a second thread:
using UnityEngine;
using System.Collections;
using System.Threading;
public class csharp_thread : MonoBehaviour {
private object oThreadLock = new object();
private int threadcounter = 0;
// Use this for initialization
void Start ()
{
System.Threading.Thread oThread = new Thread(new ThreadStart(ThreadFunc));
oThread.IsBackground = true;
// Start the thread
oThread.Start();
}
void ThreadFunc()
{
while (true)
{
Thread.Sleep(1000);
lock (oThreadLock)
{
threadcounter++;
}
}
}
// Update is called once per frame
void Update () {
lock (oThreadLock)
{
Debug.Log("Threadcounter = " + threadcounter);
}
}
}