最終我會做出(雖然有點醜但還可以動XD)
上面版本只做了 查尋,新增,刪除 (修改自行補上XD)
在開始前先將所使用的資料庫匯入 資料庫腳本路徑

匯入完成後打開Unity3D


簡單分層
- Model:資料對應
 - Dao:連接資料庫相關
 - Script:Unity3D腳本
 
直搗核心連接資料庫類別  SQLHelper.cs

先把需要使用的命名空間寫進來
using Dapper;
using Mono.Data.Sqlite;
using UnityEngine;
using System.Data;
SQLHelper類別使用設計模式:門面模式
- 原因:使用第三方插件,最好再多包一層
 
- 日後第三方插件做修改只需要改一個地方
 - 日後可能不只連接SQLite,還可能連MSSQL.統一管理可幫助日後提取抽象
 
/// <summary>
/// 把Dapper多包一層,專門做Dapper操作
/// </summary>
public class SQLHelper
{
    //連接資訊
    private string _Connstring;
    public SQLHelper()
    {
        string dbPath = string.Format("{0}/Data/{1}"
            ,Application.dataPath//取得執行程式跟目錄
            ,"Info.db"); //取得DB
        _Connstring  = string.Format("Data Source={0};Version=3;",dbPath);
    }
    public IEnumerable<T> Query<T>(string SqlText, object para = null)
    {
        return SQLExcute((conn)=>conn.Query<T>(SqlText, para));
    }
    public int Excute(string SqlText, object para = null)
    {
        return SQLExcute((conn) => conn.Execute(SqlText, para));
    }
    private T SQLExcute<T>(Func<IDbConnection, T> sqlExcutor)
    {
        using (IDbConnection conn = new SqliteConnection(_Connstring))
        {
            //2.打開連接
            conn.Open();
            //3.執行查詢
            return sqlExcutor(conn);
        }
    }
}
在建構子初始化連接資訊
- Application.dataPath 可以取得執行跟目錄
 
寫完基礎建設後,剩下就是使用啦XD
在創建一個PersonDAO來統一操作Person資料庫操作
public class PersonDao
{
    SQLHelper _sqlHelper = new SQLHelper();
    /// <summary>
    /// 取得Person列表
    /// </summary>
    /// <returns></returns>
    public IEnumerable<PersonModel> GetPersonInfo()
    {
        string sqlText = "SELECT Rowid,Name,Age From Person";
        return _sqlHelper.Query<PersonModel>(sqlText, null);
    }
    /// <summary>
    /// 新增一個Person
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public int AddPerson(PersonModel model)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("INSERT INTO Person (NAME,AGE) ");
        sb.AppendLine("Values ");
        sb.AppendLine("(@NAME,@AGE) ");
        return _sqlHelper.Excute(sb.ToString(), model);
    }
    /// <summary>
    /// 刪除Person資料
    /// </summary>
    /// <param name="Rowid"></param>
    /// <returns></returns>
    public int DeletePerson(int Rowid)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("Delete FROM Person ");
        sb.AppendLine("WHERE Rowid = @Rowid ");
        return _sqlHelper.Excute(sb.ToString(), new { Rowid = Rowid });
    }
}
InfoScript 這個腳本初始化 使用者表格的資訊
因為Unity腳本不能使用建構子 所以腳本初始化必須在Start或Awake中使用
- 初始化使用者預置體 
GameObject person = Instantiate(PersonPrefab); - 把使用者資料附值上使用者物件 
person.GetComponent().SetPersonInfo(item);  - 使用者物件設置到UI的PersonTable
 
public static InfoScript Instance;
public GameObject PersonPrefab;
public Transform PersonTable;
// Use this for initialization
void Start ()
{
    Instance = this;
    Init();
}
public void Init()
{
    Clear();
    PersonDao helper = new PersonDao();
    int index = 1;
    foreach (var item in helper.GetPersonInfo())
    {
        GameObject person = Instantiate(PersonPrefab);
        person.GetComponent<PeronScript>().SetPersonInfo(item);
        //設置父物件
        person.transform.SetParent(PersonTable);
        //設置Person位置
        person.GetComponent<RectTransform>().transform.localPosition =
            new Vector2(0, -index * 40); //Vector2(x軸,y軸)
        index++;
    }
}
private void Clear()
{
    foreach (Transform child in PersonTable.transform)
    {
        Destroy(child.gameObject);
    }
}
PeronScript 腳本
SetPersonInfo 方法初始化使用者資訊,並添加按鈕事件
public class PeronScript : MonoBehaviour
{
    public GameObject Age;
    public GameObject Name;
    public GameObject RowId;
    public Button DeleteBtn;
    public InputField Input_Age;
    public InputField Input_Name;
    private PersonModel personInfo;
    private PersonDao _personDAO;
    void Awake()
    {
        _personDAO = new PersonDao();
    }
    /// <summary>
    /// Person物件初始化
    /// </summary>
    /// <param name="personModel"></param>
    public void SetPersonInfo(PersonModel personModel)
    {
        Age.GetComponent<Text>().text = personModel.Age.ToString();
        Name.GetComponent<Text>().text = personModel.Name;
        RowId.GetComponent<Text>().text = personModel.Rowid.ToString();
        personInfo = personModel;
        Button btn = DeleteBtn.GetComponent<Button>();
        btn.onClick.AddListener(DeletePerson);
    }
    /// <summary>
    /// 新增Person方法
    /// </summary>
    public void AddPerson()
    {
        //Input Age
        string age = Input_Age.text;
        //Input Name
        string name = Input_Name.text;
        _personDAO.AddPerson(new PersonModel()
        {
            Age = age.IntOrDefault(),
            Name = name
        });
        InfoScript.Instance.Init();
    }
    /// <summary>
    /// 刪除Person方法
    /// </summary>
    public void DeletePerson()
    {
        _personDAO.DeletePerson(personInfo.Rowid);
        InfoScript.Instance.Init();
    }
}
總結: Unity3D使用資料庫和asp.net基本上是一樣,所以可說是無痛接軌XD
在撰寫Unity程式時我發覺很多地方都會用到 設計模式 (不知不覺長出來XD)
希望這篇可以幫助到在Unity3D要Sqlite+Dapper的小夥伴!!
如果本文對您幫助很大,可街口支付斗內鼓勵石頭^^

