multithread constructor call create gameObject

Hi. When I’m trying to create gameobject in constructor I get the following error:

Internal_CreateGameObject 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.

How could I do it so that I could create a gameObject by calling a constructor from multithread using javascript?

I’m making an MMO client side using Unity and that’s why I must use multithreading to read data from the server and construct players from the incomingdata.

You can’t use any Unity API from another thread. You have to execute those things on the main thread. You can use WhyDoIDoIt’s Loom class(i mirrored it on my dropbox since his website is down). Just keep in mind that you have to call Initialize somewhere on the main thread (Start / Awake):


Now you can simply schedule things on the main thread by passing a delegate to “QueueOnMainThread”. You can use lambdas as well.

// inside another thread:
    // Use the Unity API here.

Of course you can’t talk forth and back between threads like that. The delegate will be invoked in Update when the Loom class iterates the scheduled tasks.

If you need to use the Unity API in another thread and you have to wait for the result you could modify the Loom class to have it return an AutoResetEvent which you signal when the scheduled delegate has been processed in Update.

Passing data can be done most easily with closures (lambda or anonymous delegate). However as said this requires you to have a wait handle (like the AutoResetEvent) since your thread has to wait for the main thread to actually process the delegate.

I’ve once created an “advanced” version of the Loom class called LoomEx. It handles the queued items more efficient in a linked list and keeps them sorted in the order they should be executed. It also provides a way to wait for the main thread to process the callback before it returns.

Thank you for great answers. I decided to make following update loop into a main thread script. Well this isn’t very efficient way of doing it, but it’s good enough for now. :slight_smile:

function Start(){
InvokeRepeating("UpdatePlayers", 0, 0.25);

function UpdatePlayers(){
	for(var player : Player in Player.players){
		if(player.playerObject == null){
			player.playerObject = new GameObject(player.username);