I've created a menu in Unity which is populated by results from an SQLite DB. However when I create the menu, the whole game freezes for a moment while it queries the DB.
To fix this, I'm trying to separate the creation of the menu and the populating of it with data (i.e. the menu will just say "loading" until the query is complete).
I have been trying to use a yield-return co-routine to do this but the game is still freezing. Below I have some pseudo-code illustrating what I am doing...
void createMenu () {
// code to create menu...
StartCoroutine(getData());
}
IEnumerator getData () {
List<string> sqlResults = Database.query("SELECT * FROM table");
yield return null;
updateMenu();
}
void updateMenu() {
// replaces "loading" strings with sql data results
}
Am I going about this the wrong way, or am I using a coroutine incorrectly?
Yes putting this code in a coroutine as you have will not change anything. Unity is single threaded, however you can start a separate thread to do some work as long as their are no calls to any Unity functions executed in that thread.
Try this:
So the problem here is that you are synchronizing with the server and not asyncying and which will make you wait for the connection or query (if it gives you something wrong or its a wrong query you'll wait till the timeout of httprequest or db request). Try to use async functions instead of enumerator or than a enumator with async fucntion call which will let you being on the menu while it is retrieving the information.
It looks like the database operation is blocking the main thread. Run it in a new Thread with the
ThreadPool.QueueUserWorkItem
function. When it's done, useUnityThread.executeInUpdate
function from this post to call theupdateMenu()
function. You need to get theUnityThread
class from this post in order to use this solution.USAGE: