Unity+Android+Sqlite

用unity开发的安卓端游戏,如果需要使用Sqlite数据库,有很多地方就需要注意。

首先我们需要一些dll库:Mono.Data.Sqlite.dll、sqlite3.dll、System.Data.dll,这三个dll库我们需要放到Assets\Plugins文件夹下,如果文件夹不存在就需要按照这个路径建立。此外,Assets\Plugins\Android这个路径下还需要libsqlite3.dll。

当dll库都导入完成后,我们就需要导入数据库文件了。数据库文件的建立这里就不多提了。在Assets下建立StreamingAssets,将数据库文件放入该文件夹下。

准备工作完成后就是代码了:

using UnityEngine;

using System.Collections;

using Mono.Data.Sqlite;

using System.IO;

public class DBAccess {

private static DBAccess instance;

private SqliteConnection dbConnection;

private SqliteCommand dbCommand;

private SqliteDataReader dbReader;

public static DBAccess Instance

{

get {

if (instance == null)

{

string dbName = Application.persistentDataPath + “/” + “Score.db”;

CopyDB(dbName);

instance = new DBAccess(“URI=file:” + dbName);

}

return instance;

}

}

private static void CopyDB(string dbName)

{

if (!File.Exists(dbName))

{

WWW loadDB = new WWW(“jar:file://” + Application.dataPath + “!/assets/” + “Score.db”);

bool boo = true;

while (boo)

{

if (loadDB.isDone)

{

File.WriteAllBytes(dbName, loadDB.bytes);

boo = false;

}

}

}

}

private DBAccess(string dbName)

{

OpenDB(dbName);

}

private void OpenDB(string dbName)

{

try

{

dbConnection = new SqliteConnection(dbName);

dbConnection.Open();

if (dbConnection.State == System.Data.ConnectionState.Open)

{

Debug.Log(“open”);

}

}

catch (UnityException e)

{

string eString = e.ToString();

Debug.Log(eString);

}

}

}

上述为打开数据库的代码。另外,在打包时注意setting中的Api Compatibility Level 要设置为.NET2.0

    原文作者:joshuaAS
    原文地址: https://www.jianshu.com/p/17284bc46654
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞