설치

아래의 링크에서 파일을 받을 수 있다.

파일을 열면 readme 파일을 제외하고 3개의 파일이 있다

3개의 파일 중에 DataTable.cs와 SqliteDatabase.cs 파일은 플러그인 폴더에 넣고 –플러그인 폴더에 SQLiteUnityKit 폴더를 만들어서 넣는다– libsqlite3.so 파일은 안드로이드 빌드용 파일이므로 plugin/android 폴더 아래에 넣는다.

DB 파일 저장 위치

게임 내에서 사용할 DB 파일을 만들었다면 Assets/StreamingAssets 폴더 아래에 둔다.

이렇게 해두면 플러그인의 코드는 StreamingAssets 폴더 아래에 있는 db 파일을 원본으로 보고, 그 파일을 유니티에서 지원하는 persistentDataPath 에 복사해서 게임 내에서 사용할 것이다.

게임 내에서 DB 파일 불러오기

게임 내에서 DB 파일을 불러 올 때는 SqliteDatabase 생성자에 db 파일의 이름을 string으로 넘기면 된다.

static SqliteDatabase vocaDB;
static SqliteDatabase quizEngDB;

static public void InitQuizDictionary ()
{
    quizEngDB = new SqliteDatabase("quiz_english.sqlite");
    vocaDB = new SqliteDatabase("vocabulary.sqlite");
}

게임 내에서 사용되는 DB 파일은 persistentDataPath에 들어가게 되는데, 만일 persistentDataPath에 DB 파일이 없다면, 플러그인 코드는 streamingAssetsPath –Assets/StreamingAssets– 에서 DB 파일을 persistentDataPath에 복사해 와서 사용할 것이다.

때문에 streamingAssetsPath에도 파일이 없으면 에러가 난다.

DB 파일 최신 버전으로 변경하기

사용하는 DB가 업데이트 되어 DB 파일을 교체 해야 하는 경우 아래와 같이 DB 파일이 변경된 것을 확인하여 갈아 치우는 로직을 사용한다.

// 일단 vocaDB 를 생성한 후에 vocaDB이 업데이트 되었는지 확인한다.
vocaDB = new SqliteDatabase("vocabulary.sqlite");
vocaDB.OverwriteOnSourceMismatch("vocabulary.sqlite");

// OverwriteOnSourceMismatch가 DB 파일 업데이트를 체크하는 부분. MD5를 이용해서 버전이 바뀌었는지를 확인한다.
public bool OverwriteOnSourceMismatch(string dbName) {
    string sourceDbPath  = System.IO.Path.Combine (Application.streamingAssetsPath, dbName);
    string currentDbPath = System.IO.Path.Combine (Application.persistentDataPath, dbName);

    if (System.IO.File.Exists(currentDbPath) && System.IO.File.Exists(sourceDbPath)) {
        String sourceDbChecksum = CreateMD5HashOfFile(sourceDbPath);
        String currentDbChecksum = CreateMD5HashOfFile(currentDbPath);

        if (currentDbChecksum != sourceDbChecksum) {
            CopyDB (sourceDbPath, currentDbPath);
            return true;
        }
    }

    return false;
}

// 버전이 바뀌었는지를 체크하는 MD5 부분.
private string CreateMD5HashOfFile(string filename)
{
    // Use input string to calculate MD5 hash
    System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
    System.IO.FileStream stream = System.IO.File.OpenRead(filename);
    byte[] hashBytes  = md5.ComputeHash(stream);

    // Convert the byte array to hexadecimal string
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    for (int i = 0; i < hashBytes.Length; i++)
    {
        sb.Append (hashBytes[i].ToString ("X2"));
        // To force the hex string to lower-case letters instead of
        // upper-case, use he following line instead:
        // sb.Append(hashBytes[i].ToString("x2"));
    }
    return sb.ToString();
}

DB 파일 사용하기