参考
- 導入編
- SQLite対応のGUIの検討
- 過去の記事(SQLite対応のGUI)
- C#とSQLiteについて
- 過去の記事(C#によるSQLiteの操作)
- UnityとSQLiteについて
- 過去の記事(SQLiteとUnity)
- データベースの周辺知識
- 過去の記事(データベースの種類や用語)
本題
1. SQLiteUnityKitの導入
冒頭参考の「導入編」リンク先の解説に従い、SQLiteUnityKitを自身のProjectに加える。ただし、SqliteDatabase.csには知っておくべき内容があるのでチェックした方が良い。下に示すのはSqliteDatabase.csのコンストラクター(初期化)を抜粋したものである。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public SqliteDatabase (string dbName) | |
{ | |
pathDB = System.IO.Path.Combine (Application.persistentDataPath, dbName); | |
//original path | |
string sourcePath = System.IO.Path.Combine (Application.streamingAssetsPath, dbName); | |
//if DB does not exist in persistent data folder (folder "Documents" on iOS) or source DB is newer then copy it | |
if (!System.IO.File.Exists (pathDB) || (System.IO.File.GetLastWriteTimeUtc(sourcePath) > System.IO.File.GetLastWriteTimeUtc(pathDB))) { | |
if (sourcePath.Contains ("://")) { | |
// Android | |
WWW www = new WWW (sourcePath); | |
// Wait for download to complete - not pretty at all but easy hack for now | |
// and it would not take long since the data is on the local device. | |
while (!www.isDone) {;} | |
if (String.IsNullOrEmpty(www.error)) { | |
System.IO.File.WriteAllBytes(pathDB, www.bytes); | |
} else { | |
CanExQuery = false; | |
} | |
} else { | |
// Mac, Windows, Iphone | |
//validate the existens of the DB in the original folder (folder "streamingAssets") | |
if (System.IO.File.Exists (sourcePath)) { | |
//copy file - alle systems except Android | |
System.IO.File.Copy (sourcePath, pathDB, true); | |
} else { | |
CanExQuery = false; | |
Debug.Log ("ERROR: the file DB named " + dbName + " doesn't exist in the StreamingAssets Folder, please copy it there."); | |
} | |
} | |
} | |
} |
注意点
- 冒頭参考の「UnityとSQLiteについて」で語られていた内容がここに当たる
- Android端末はStreamingAssetsに直接アクセスできない
- データベースをPersistentDataPathにコピーする
- これによりAndroid・iOS共に同じ記述で処理できるようになる
- コピーが起きる条件は下記のいずれかである(上記スクリプトの9行目)
- 引数で受け取った名前のファイルがPersistentDataPathに無い場合
- ファイルの更新日を比較して、PersistentDataPathの方が古い場合
特にファイルの更新日でデータベースが上書きされてしまうのが厄介。File.Copyの第3引数のtrueは「上書き保存を許可する」の意味である。これにより、端末に保存したユーザーデータが簡単にリセットされてしまう。
コピー条件の後者は削除して、「ファイルが存在しない時のみコピー」とした方が無難。完全に書き換えたい場合は、PersistentDataPathのファイルを削除すれば良い。これにより同名のファイルが無くなるので、StreamingAssetsからコピーされる。なお、こちらのサイトでは引数を増やして対応していた。
0 件のコメント:
コメントを投稿