Hello.
I’m trying to load a screen in background into a new thread.
But it gives me this error:
"LoadLevelAsync can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function."
Thank you very much for your answer, here is the code:
using UnityEngine;
using System.Collections;
public class Loading : MonoBehaviour {
public static string levelName;
System.Threading.Thread newThread = new System.Threading.Thread(AMethod);
public bool inRoutine = false;
private static void AMethod(object obj)
{
Application.LoadLevel(levelName);
}
void Start () {
newThread.Start();
StartCoroutine(waitTwoseconds());
}
void Update () {
if(inRoutine == true)
{
inRoutine = false;
}
}
IEnumerator waitTwoseconds(){
yield return new WaitForSeconds(2f);
inRoutine = true;
}
}
In this way if i’ve understood how multithreading in c# works, at the start of newThread it should start doing the code into aMethod right?
but it still gives me that error of loadAsync, even if i don’t use it no where in my code.
The problem is that everything that is related to the unity engine (with only very view exceptions) have to be called from the main thread.
If you use Application.LoadLevel , the engine will use all his resources to load the new level. This will cause the current level to grind to a halt.
If you use Application.LoadLevelAsync unity will load the level in the background while letting the current level still running until the next level is completely loaded. This may cause a little studding but not halting the current level like in the case of Application.LoadLevel.
You can use multitasking for heavy not directly unity related calculations and than ship the result back to the main thread for the unity interaction.
So multithreading does not exist in Unity. You can create your own but you might run into issues (I have not done testing of this on multiple platforms). An unfortunate thing is almost all of Unity’s functions are not thread safe. That is what this error is upset about. You can’t call any of Unity’s functions while not on the main thread.
What you do use a Coroutine. A Coroutine is a time share (it fakes being multithreaded). To use LoadLevelAsync you do this
IEnumerator waitTwoseconds()
{
AsyncOperation async = Application.LoadLevelAsync("My level name");
yield return async; //Wait for your level to load
//Level is loaded
}