I'm trying to instantiate some prefabs in my scene, I'm forced to do it in a function (not main thread) because I instantiate a prefab only when I receive some data throught an TCP protocol.
Right now, I'm just testing with a cube prefab, but it's not working :
private void addAircraft(Plane plane)
{
listPlane.Add(plane);
//THIS 2 LINES ARE THE PROBLEM
GameObject cube = Instantiate(Resources.Load("Cube", typeof(GameObject))) as GameObject;
cube.transform.position = new Vector3((float)plane.X, 0, (float)plane.Y);
//
planeId_Object_Dictionnary.Add(plane.Flight, cube);
Debug.Log("Plane " + plane.Flight + " is added");
}
It return me the error :
Load 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.
Even if, a lot of people have encounterd this problem, I can't find a solution that allows me to instantiate my prefab in a function.
You could have a private bool checker to see if the plane should be added at any time. When you receive TCP response mark it true, call addAircraft() from the Update() function and mark it false again. Update() runs on main thread so this will make sure addAircraft() also runs on main thread.
I guess 1 frame delay wouldn't matter if you're waiting anyways.