SetActive can only be called from the main thread

Hello, im making online games with socket.io. I have problem on function call backs. Can someone help me for fix this problem ?

Login callback working correctly.

void LoginCallBack(SocketIOEvent e) {
        JSONObject data = e.data;
        if (data.GetField("msg").ToString().Contains("Logined")) {
            mScript.Logined();
        }
}

Here is the mScript.Logined() function:

public void Logined() {
        OpenScreen(3);
}

This functions working correctly. But ErrorCallBack returning error “SetActive can only be called from Main Thread”

void ErrorCallBack(SocketIOEvent e) {
        mScript.SocketError();
}

Here is the mScript.SocketError() function:

public void SocketError() {
        OpenScreen(2);
}

OpenScreen function:

void OpenScreen(int id) {
        for (int i = 0; i < uiScreens.Length; i++) {
            if (i == id) {
                uiScreens[i].gameObject.SetActive(true);
            } else {
                uiScreens[i].gameObject.SetActive(false);
            }
        }
}

Asynchronous callbacks often happen on a different thread. There are a couple of ways you can get back to the main thread.

Use a queue

If you are doing this a lot, have a collection of actions. The callback function can add a new action to the collection. Then have a MonoBehaviour that checks in Update for any actions in the collection, and executes them.

Use a coroutine

You can wrap the whole thing in a coroutine. Call the async method from a coroutine. Have a bool that the async method sets to true when it’s done. Then in your coroutine yield until the bool is true. Then di the Unity specific stuff.

1 Like

I read this in the rhythm of rap.

2 Likes

Are you serious with me right now?
this is one heck of a necro.

2 Likes