使用协程访问Unity中的SQLite数据库 [英] Accessing SQLite database in Unity with a coroutine
问题描述
我已经在Unity中创建了一个菜单,该菜单由SQLite DB的结果填充.但是,当我创建菜单时,整个游戏在查询数据库时冻结了片刻.
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).
我一直在尝试使用yield-return协同例程来执行此操作,但是游戏仍然处于冻结状态.下面我有一些伪代码来说明我在做什么...
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?
推荐答案
数据库操作似乎阻塞了主线程.使用ThreadPool.QueueUserWorkItem
函数在新线程中运行它.完成后,使用此帖子,以便使用此解决方案.
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, use UnityThread.executeInUpdate
function from this post to call the updateMenu()
function. You need to get the UnityThread
class from this post in order to use this solution.
void Awake()
{
UnityThread.initUnityThread();
}
void runQuery(string query)
{
ThreadPool.QueueUserWorkItem(RunInNewThread, query);
}
private void RunInNewThread(object a)
{
string query = (string)a;
List<string> sqlResults = Database.query(query);
//We are in another Thread. Use executeInUpdate to run in Unity main Thread
UnityThread.executeInUpdate(() =>
{
updateMenu();
});
}
用法:
runQuery("SELECT * FROM table");
这篇关于使用协程访问Unity中的SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!