I was using the SynchronizationContext.Current to send a function from a background thread to the main thread e.g. to create a gameobject.
See this code sample:
// Context from main thread:
var syncContext = SynchronizationContext.Current;
// runs on main thread - works:
var sphere0 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
// create GameObject from background task:
await Task.Run(
() =>
{
syncContext.Post(
s =>
{
// works:
var sphere1 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
},
null);
});
await Task.Run(
() =>
{
syncContext.Send(
s =>
{
// does NOT work:
var sphere2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
},
null);
});
The Post method (fire-and-forget) works, but the Send fails with
CreatePrimitive 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.
UnityEngine.GameObject:CreatePrimitive(PrimitiveType)
How come?
Thanks for any help.