You should be doing expensive queries in another Thread. Once the query returns, you can use the result in the main Thread
. I noticed you made attempt to use Thread
but you're getting new error:
get_persistentDataPath can only be called from the main thread.
This is because you're using Application.persistentDataPath
in another Thread
. You cannot use most Unity API in another Thread
and Application.persistentDataPath
is one of them. This is a simple fix. There is no reason to use Application.persistentDataPath
in another Thread. Get the value of Application.persistentDataPath
and store in in a global string
variable then use that global variable in the new Thread.
For example:
Don't do this ( this is what you're currently doing):
void Start()
{
//This Start function is the main Thread (Unity's Thread)
var thread = new System.Threading.Thread(() =>
{
//This is another Thread created by you
//DO NOT DO THIS(Don't use Unity API in another Thread)
string dbPath = Application.persistentDataPath;
//do sqlite operations
});
thread.Start();
}
Do this instead (Get the variable of Application.persistentDataPath
in the main thread before then use the stored value):
void Start()
{
//This Start function is the main Thread (Unity's Thread)
//Get path in the Main Thread
string dbPath = Application.persistentDataPath;
var thread = new System.Threading.Thread(() =>
{
//This is another Thread created by you
//Use the path result here
//do sqlite operations
});
thread.Start();
}
Finally, if you really need to use many other Unity API other than Application.persistentDataPath
or for example, update the UI Text component with result from the database, you can use my UnityThread
plugin which simplifies that.
public Text yourTextComponent;
void Start()
{
UnityThread.initUnityThread();
//This Start function is the main Thread (Unity's Thread)
//Get path in the Main Thread
string dbPath = Application.persistentDataPath;
var thread = new System.Threading.Thread(() =>
{
//This is another Thread created by you
//do sqlite operations
//Show result on UI
UnityThread.executeInUpdate(() =>
{
yourTextComponent.text = queryResult;
});
});
thread.Start();
}