floatinghotpot / socket.io-unity

socket.io client for Unity, power game client with node.js back-end
494 stars 76 forks source link

Cannot instantiate prefab. #39

Open Herbias opened 5 years ago

Herbias commented 5 years ago

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

Here's my code snippet socket.On("get_user_online_companion", (data) => { Instantiate(otherUserPrefab); });

I attempt to instantiate it in Update() but when it is instantiate it is automatically destroy and also I cannot use coroutine. I would like to know I can get the source code and try to port it to the latest unity build.

nadir500 commented 5 years ago

did you find the solution?

I am facing the same problem

Gradner commented 4 years ago

I ran into this issue, and it looks like it's caused by the socket callback being handled outside of Unity's Main Thread. Unfortunately, Instantiate calls can only be done from the main thread.

Unity doesn't seem to log the error, whether it's because it's called outside the main thread or if that's intended behaviour with Instantiate(), but if you make sure you're Using System; at the top of your script, you can throw your instantiate inside a try catch statement and log the exception:

try { Instantiate(otherUserPrefab); } catch(Exception e) { Debug.Log(e); }

and it should log out your error.

If it is the same Main Thread issue I ran into, there are a lot of different ways to force unity to use the main thread to dispatch certain functions, but I went ahead and used This Script to provide an easy 1-line interface for it.

Once you have that prefab added to your scene, just call it like this:

socket.On("get_user_online_companion", (data) => { UnityMainThreadDispatcher.Instance().Enqueue(Instantiate(otherUserPrefab)) });