As many Unity developer already knows, Unity's logic runs in main thread. When you need network feature in your project you probably use socket or other network library. Of course when you send/receive some packets over the network, you will use non-blocking or asynchronize mechanism.
Normally we use callback or event function and those are called by OS. Ok then you can do whatever you want. Something like this.
void MyReceiveFunction(data)
{
// ok, I received a data!
if ( data == 0 )
{
foo(0);
}
else if ( data == 1001 )
{
foo(1001);
}
else
{
...
}
}
The problem is that the function is called on different thread. (which is not mianthread)
so If you do anything that it is related with main thread or GUI, logic won't run correctly. The pattern I'm going to talk about is saving this situation! (very simple)
void MyReceiveFunction(data)
{
// ok, I received a data!
if ( data == 0 )
{
reserveFoo(0);
}
else if ( data == 1001 )
{
reserveFoo(1001);
}
else
{
...
}
}
in the reserveFoo function we can reserve the command like below.
void reserveFoo(int cmd)
{
lock
{
reserveFooList.add(cmd);
}
}
reserveFooList is a container. It store a cmd. and it is used in consumer logic in mainthread.
// Update function is called in main thread.
void Update()
{
if ( reserveFooList.size > 0 )
{
foreach(element : reserveFooList)
{
Foo(element);
}
reserveFooList.clear;
}
}
Now Update function is called in main thread and checks whether size of reserveFooList is greater than 0 which means it has some element to do.
if the list is not empty then iterate all the elements and process those in main thread. That's is the main idea.
Of course you can use invoke method for solve this issue but personally I prefer to do this.
Subscribe to:
Post Comments (Atom)
Task in UnrealEngine
https://www.youtube.com/watch?v=1lBadANnJaw
-
Unity released very good FPS example for people and I decided to analysis how they make this. Personally I wanted to show you how I analys...
-
When we use DrawDebugSphere function for debugging, it is working well but when you are trying to use it in anim node's function it will...
-
If you press a key 'L' in the jupyter notebook then you can see the line number in the editor.
No comments:
Post a Comment