itisnajim / SocketIOUnity

A Wrapper for socket.io-client-csharp to work with Unity.
MIT License
393 stars 67 forks source link

[Question] How to make sure socket.EmitAsync("MySocketMessage", response, params) is done properly #21

Closed ThimoDEV closed 2 years ago

ThimoDEV commented 2 years ago

Hi @itisnajim

I'm using socket.EmitAsync(message, response => { assigning some data in here bool Foo = response.getValue(); }, params);

if (Foo is true ) { DoMyActionBasedOnFoo(); }

However, depending on how heavy the task is my if statement is executed earlier than Foo is assigned, resulting in nullreferenceExceptions etc.

Do you know how I can assure the EmitAsync method is fully done and back on the right thread? so the order of execution is as I want?

itisnajim commented 2 years ago

Even if the emitting is async, but the response callback idk about it..,

So just check the Foo every time you got the response so that way you will not get into exceptions: bool Foo = response.getValue(); checkAndDoAction();

You can add a global bool if you want to execute the action method only one time. if(!isActionExecuted){ checkAndDoAction(); isActionExecuted = true; }

ThimoDEV commented 2 years ago

I have a feeling the response code is running on another thread and not the unity main thread, so how did you have in mind checking Foo everytime? Cause my method right now is already finished by the time the response is received.

itisnajim commented 2 years ago

I mean you have to do the check and the action method in the response callback response => { /* here */ }, not after the whole socket.EmitAsync(...); thing ... And you can use the executeInUpdate function if you have something needed to be executed in the main thread!

UnityThread.executeInUpdate(() => {
    objectToRotate.transform.Rotate(0, 45, 0);
});

@ThimoDEV Happy coding :)

ThimoDEV commented 2 years ago

@itisnajim Thank you!

I thought "unityThreadScope = SocketIOUnity.UnityThreadScope.Update" was fixing the main thread executing but thats not completely the case. Now it works exactly as I want.

Thank you for your always fast response! <3 I will close this issue now as resolved.