How to solve unity error "Invoke can only be called from the main thread"?

2.7k Views Asked by At

I am using Appwarp api for a multiplayer game. I am getting an error when i am calling Invoke("recoverConnection", 5).

public void onConnectDone(ConnectEvent eventObj)  
{  
    Log ("onConnectDone : " + eventObj.getResult ());  

    if (eventObj.getResult () == 0)   
    {
        recoveryErrorCode = 0;  
        WarpClient.GetInstance ().JoinRoomInRange (0, 5, true);  
    }   
    else if (eventObj.getResult () == 9)  
    {  
        this.Invoke("recoverConnection", 5);  
    }  
    else if (eventObj.getResult () == 8)   
    {  
        // reconnected  
    }  
}  

void recoverConnection()
{
    WarpClient.GetInstance ().RecoverConnection ();
}

The error is :

Invoke can only be called from the main thread.

Constructors and field initializers will be executed from the loading thread when loading a scene.

1

There are 1 best solutions below

1
Rajeev On

The callback onConnectDone is called on a separate thread so any UI related changes or Invoke functionality need to be called on main thread. You can use any plugin which can help you to call any method on main thread from any secondary thread. You can have a look at this link. This will help you to call Invoke method from main thread.

I hope this will help you.