this register function send request to server and and then login. I need write some unity logic after connect and login, such as show a loading when request start, cache user data. What is the correct way to handle those kind of things in Unity?
and also, this the code example above will log “test” firstly, then log “successfully logged in”. Why is that?
The Register() function is called with the lambda, then the Debug.Log() is called.
Sometime (when Register finishes), it will call one of the two lambdas. That’s why it’s in that order.
Look up lambdas in general. It’s basically an anonymous function created right there in place, and you had a pointer to that function into the function you are calling, and that function can later on call your lambda, usually to pass up data or events.
Thanks for your answers, I got your point. However, in the register function, it calls the server. The first lambda receives successful session. What I want to do here is to cache the session, do some ui changes(pop up a message that login success), thenload next scene(SceneManager.LoadScene(1);
). I thought I could do it in the lambda function, however, it troughs an error, LoadsceneAsyncNameIndexInternal can only be called from the main thread.
When you have something like this, basically you need to make a queue of messages of some kind and in your lambda callback, throw the message into that queue.
Then in the main thread (usually in some Update() function on some GameObject), empty out that queue and process those messages, doing whatever main thread necessary stuff you want to do.
Be sure to use lock() on your queue at the enqueue and dequeue steps in order safely deconflict the threads. Keep the enqueue and dequeue operations as short and simple as possible, i.e., have the object all prepared ahead of time before you stick it in the queue, lock it and encqueue it. Same at the receiving end: lock the queue, dequeue the object, exit the lock block, and then process your object. There is a TON of best practices out there for this sort of thing, just gotta google it.