I have a database in "Assets/Resources/db.sqlite" and I want to copy this to the PersistentDataStorage if it doesn't already exist there (Windows, Android and IOS):
private const string DatabaseName = "db.sqlite";
private string FullPersistentDataBasePath { get { return Application.persistentDataPath + "/" + DatabaseName; } }
private bool HasDatabase()
{
bool result = File.Exists(FullPersistentDataBasePath);
Debug.Log("Has persistent database already: " + result);
return result;
}
// Copy from Assets/Resources ==> PersistentDataPath
private void CopyDatabase()
{
// ? How to do this for Windows, Android and IOS? TextAsset? BinaryFormatter? How?
// var db = Resources.Load(DatabaseName);
}
I use the latest stable Unity (version 2019.3.11f1).
Final solution:
using DataBank; // My namespace that contains my SQLiteHelper
using System.IO;
using UnityEngine;
public class CopyDatabase : MonoBehaviour
{
public TextAsset DatabaseInResource = null;
private void Awake()
{
GotoScene.CanGotoNextScene = false;
if (!HasUp2DateDatabase())
{
Copy();
}
GotoScene.CanGotoNextScene = true;
}
private bool HasUp2DateDatabase()
{
// TODO: check database version also.
return File.Exists(SqliteHelper.FullPersistentDatabasePath);
}
private void Copy()
{
if (DatabaseInResource == null)
{
throw new System.NullReferenceException("DatabaseInResource is null.");
}
byte[] data = DatabaseInResource.bytes;
File.WriteAllBytes(SqliteHelper.FullPersistentDatabasePath, data);
}
}
↧