- Home /
Is it legit to make a blocking call inside of an Update() function?
Is it legit to make a blocking call inside of the Update function? Will it negatively affect somehow the program flow? For example, what happens if i put a Socket.Accept() inside of the Update function? I'm asking this since Unity just freezes when i do it
Answer by pako · May 29, 2015 at 02:01 PM
Unity freezes because it's waiting for the Socket.Accept() call to return, before it executes the next line of code in Update().
You'd better place the Socket.Accept() call inside a coroutine. Here's some example code to get you started:
void Update ()
{
StartCoroutine(SocketAccept(newListeningSocket)); //SocketAccept() gets called and code execution continues immediately
}
IEnumerator SocketAccept(Socket listeningSocket)
{
Socket mySocket = listeningSocket.Accept();
//other code...
yield return null;
}
Some references for more details:
http://docs.unity3d.com/Manual/Coroutines.html
https://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines
Answer by karl_jones · May 29, 2015 at 12:56 PM
If you block/delay in the update then you will have an impact. The update is called each frame and wont move onto the next frame until it is completed so if you block then you are potentially reducing your frame rate.
True. It is customary to put network code in a separate thread for exactly the reason you're describing.