"SetActive can only be called from the main thread"

Hi all!
I'm trying to port my Unity game to Windows Store. Sometimes, running the Visual Studio project generated by Unity, the game crashes with the following error:
[quote]
First-chance exception in 0x77462F71 in Template.exe: Exception Microsoft C++: Platform::InvalidArgumentException ^ in memory position 0x0FB8EC3C. HRESULT:0x80070057
WinRT informations: SetActive 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.
[/quote]
This error raises just sometimes, while other times the game runs without crashing. Here is the piece of code that raises the exception:

#if NETFX_CORE
    async
#endif
    public void Foo()
    {
        ...
#if !NETFX_CORE
        if (Bar())
#else
        if (await Bar())
#endif
        {
            myGameObject.SetActive(true); // THIS INSTRUCTION RAISES THE EXCEPTION
        }

        ...
    }

It seems to me that the problem is that sometimes the "myGameObject.SetActive(true)" instruction is executed into another thread, but I don't understand how it can happen.
What's wrong with my code?
Thank you in advance for your help!

As the error says you're calling "myGameObject.SetActive(true); " from the wrong thread, to fix this you must use InvokeOnAppThread, something like this:

WSAApplication.InvokeOnAppThread(()=>
{
   myGameObject.SetActive(true);
}
2 Likes

await transfers control to another thread.

1 Like

Thank you both for your answers! :slight_smile:
So, if I understood correctly, inside an async method every UnityEngine’s method call must be wrapped into InvokeOnAppThread()?

1 Like

Yes, because most of the UnityEngine API is not thread-safe, so you must call them in the correct thread - also known as app thread in this case.

2 Likes

Ok, good to know. Thank you very much for your precious help! :)