socket.io-unity icon indicating copy to clipboard operation
socket.io-unity copied to clipboard

Cannot instantiate prefab.

Open Herbias opened this issue 7 years ago • 2 comments

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.

Herbias avatar Nov 14 '18 14:11 Herbias

did you find the solution?

I am facing the same problem

nadir500 avatar Apr 25 '19 21:04 nadir500

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)) });

Gradner avatar Jan 28 '20 01:01 Gradner