Unity教程之-Unity数据持久化

 

如何解决Unity中的数据持久化呢,本篇unity教程我们来学习两种方法来解决unity中数据持久化问题

方法一:利用Unity自带的函数PlayerPrefs,这种方法Windows会把其资料储存在注册表里。此程式并不是唯一储存资料的办法,但却简单使用,使用如下


private string save1 ="";
private string read1="";
void OnGUI (){

save1 = GUILayout.TextField (save1, GUILayout.Width (200));

if (GUILayout.Button (“Save”)) {

PlayerPrefs.SetString (“save1”, save1);//设定“save1”空间,并存入save1变数的字串资料

PlayerPrefs.Save ();//存档


}

if (GUILayout.Button (“Read”)) {

read1 = PlayerPrefs.GetString (“save1”);//把“save1”空间的资料取出,存入read1变数里

}

GUILayout.Label (read1);
if (GUILayout.Button (“Delete key”)) {

PlayerPrefs.DeleteKey (“save1”);//删除“save1”空间的资料
}
if (GUILayout.Button (“Delete all keys”)) { Unity3D教程手册

PlayerPrefs.DeleteAll ();//删除所有存档

}

}

方法二,在unity中利用sqllite轻量级数据库,读取Sqlite数据库首先需要一个sqlite的DLL文件,在Unity安装目录可以找到。

下面贴上数据操作代码


using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System;

public class Helper : MonoBehaviour {

private SqliteConnection mSqliteConnection;
private SqliteCommand mSqliteCommand;
private SqliteDataReader mSqliteDataReader;

// Use this for initialization
void Start () {

//打开数据库
try
{
string dbpath=Application.dataPath+"/game.db";
mSqliteConnection = new SqliteConnection("URI=file:"+dbpath);
mSqliteConnection.Open();
}
catch(Exception e)
{
Debug.Log(e.ToString());
}

//查询一个数据
string sqlquerystr = "select * from type_skill_attribute where id < 30";
mSqliteCommand = mSqliteConnection.CreateCommand ();
mSqliteCommand.CommandText = sqlquerystr;
mSqliteDataReader = mSqliteCommand.ExecuteReader ();

while(mSqliteDataReader.Read())
{
int customid=mSqliteDataReader.GetOrdinal("skill_id"); //获取列ID,从0开始
Debug.Log("customid = "+customid);
int skill_id=mSqliteDataReader.GetInt32(customid);

customid=mSqliteDataReader.GetOrdinal("type");
Debug.Log("customid = "+customid);
string type=mSqliteDataReader.GetString(customid);

Debug.Log("skill_id = "+skill_id+" type = "+type);
}

mSqliteDataReader.Close ();
if(mSqliteCommand!=null)
{
mSqliteCommand.Dispose ();
}
if(mSqliteConnection!=null)
{
mSqliteConnection.Close ();
mSqliteConnection = null;
}
}

// Update is called once per frame
void Update () {

}
}