码迷,mamicode.com
首页 > 编程语言 > 详细

Unity游戏开发学习之路——数据持久化

时间:2017-03-09 22:48:23      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:静态   zha   写入   cti   body   conf   win   报错   文件   

数据持久化

  谈到数据持久化,在Unity的游戏开发中十分重要的,不管是是在本地和服务器端,数据持久化都是我们学习的难点,数据持久化的技术有很多种,这里只选取几种,目前也是我所学到的,在接下来的时间里会陆续整理到这里。

Part1:PlayerPrefs类

  这是unity圣典中给出的,

PlayerPrefs 游戏存档
Description 描述

在游戏会话中储存和访问游戏存档。这个是持久化数据储存,比如保存游戏记录。

Editor/Standalone 编辑器 / 桌面平台

Mac OS

在Mac OS X上PlayerPrefs是存储在~/Library/Preferences文件夹,名为unity.[company name].[product name].plist,其中company name和product name名是在Project Setting中设置,.plist文件可用于编辑器和桌面平台运行。 (打开Find,按住Option键,点击“前往 →“资源库”,就可以找到Preferences文件夹。)

Windows

在Windows平台下,PlayerPrefs被存储在注册表的 HKEY_CURRENT_USER\Software\[company name]\[product name]键下(打开“运行”输入regedit打开注册表),其中company name和product name名是在Project Setting中设置。

Linux

在Linux,PlayerPrefs是储存在~/.config/unity3d/[CompanyName]/[ProductName]。其中CompanyName和ProductName名是在Project Setting中设置

Windows Store

在Windows Store,PlayerPrefs是储存在%userprofile%\AppData\Local\Packages\[ProductPackageId]>\LocalState\playerprefs.dat。

Windows Phone

在Windows Phone 8,PlayerPrefs是储存在应用自己的文件夹,参见:Windows.Directory.localFolder

WebPlayer 网页

在网页平台,PlayerPrefs是储存在二进制文件,看下面的对应的各平台位置:

Mac OS X: ~/Library/Preferences/Unity/WebPlayerPrefs

Windows: %APPDATA%\Unity\WebPlayerPrefs

一个游戏存档文件对应一个web播放器URL并且文件大小被限制为1MB。如果超出这个限制,SetInt、SetFloat和SetString将不会存储值并抛出一个PlayerPrefsException异常。

Static Functions 静态函数

DeleteAll	Removes all keys and values from the preferences. Use with caution. 
从游戏存档中删除所有key。请谨慎使用。
DeleteKey	Removes key and its corresponding value from the preferences. 
从游戏存档中删除key和它对应的值。
GetFloat	Returns the value corresponding to key in the preference file if it exists. 
如果存在,返回游戏存档文件中key对应的浮点数值。
GetInt	Returns the value corresponding to key in the preference file if it exists. 
如果存在,返回游戏存档文件中key对应的整数值。
GetString	Returns the value corresponding to key in the preference file if it exists. 
如果存在,返回游戏存档文件中key对应的字符串值。
HasKey	Returns true if key exists in the preferences. 
如果key在游戏存档中存在,返回true。
Save	Writes all modified preferences to disk. 
写入所有修改参数到硬盘。
SetFloat	Sets the value of the preference identified by key. 
设置由key确定的浮点数值。
SetInt	Sets the value of the preference identified by key. 
设置由key键确定的整数值。
SetString	Sets the value of the preference identified by key. 
设置由key确定的字符串值。

  下面我通过写的一小段代码呈现一下怎么使用:

    

public class Person
{
    /// <summary>
    /// 用于存储名字
    /// </summary>
    private string name;

    /// <summary>
    /// 运用属性的特征去存储一个变量到PlayerPrefs中,数据持久化
    /// </summary>
    /// <value>The name.</value>
    public string Name
    {
        get{ 
            return PlayerPrefs.GetString ("Name");
        }

        set{
            PlayerPrefs.SetString ("Name", value);
            PlayerPrefs.Save ();
        }
    }

    /// <summary>
    /// 返回年龄
    /// </summary>
    private int age;

    public int Age{
        get{
            return PlayerPrefs.GetInt ("Age");
        }

        set{
            PlayerPrefs.SetInt ("Age", value);
            PlayerPrefs.Save ();
        }
    }

    /// <summary>
    /// 无参数的构造函数
    /// </summary>
    public Person()
    {

    }

    /// <summary>
    /// 有参数的构造函数
    /// </summary>
    /// <param name="_name">Name.</param>
    /// <param name="_age">Age.</param>
    public Person(string _name,int _age)
    {
        this.Name = _name;
        this.Age = _age;
    }


    public override string ToString ()
    {
        return string.Format ("[Person: Name={0}, Age={1}]", Name, Age);
    }
}

将数据存储到属性中,也是一个不错的方法。这里需要注意的是设置了值后,调用Save()方法。

Part2:Json数据持久化

  首先需要用到一个json的动态链接库,JsonFx,网上可以找到,这里给出一个百度盘的连接链接: https://pan.baidu.com/s/1kVmc4Qz 密码: kqg2

然后就是把这个动态链接库导入到我们的工程的Plugins目录下面,引用即可。以下是代码部分

  这个是要用json 转化的目标类,

using System.Collections;
using System.Collections.Generic;

public class Body
 {
    
    public string name;
    public int age;

    public Body()
    {

    }

    public Body(string _name,int _age)
    {
        this.name = _name;
        this.age = _age;
    }


    public override string ToString ()
    {
        return string.Format ("[Body:name:{0},age:{1}]",name,age);
    }
}

 

下面这个类是用于转化的的测试类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using JsonFx.Json;
using System.IO;

public class TestJson : MonoBehaviour
 {

    /// <summary>
    /// 静态字段保存路径
    /// </summary>
    static string pathdata="/data.txt";

    void Start()
    {
        Debug.Log(Application.dataPath);

        Write ();
        Read ();

    }


    /// <summary>
    /// 写入json数据,将类序列化
    /// </summary>
    public static void  Write()
    {
        Body body=new Body ("zhangsan",25);

        string text = JsonWriter.Serialize (body);

        File.WriteAllText (DataPathTest.GetDataPath ()+pathdata, text);
    }

    /// <summary>
    /// 将文本反序列化为一个类
    /// </summary>
    public static void Read()
    {
        string str = File.ReadAllText (DataPathTest.GetDataPath () +pathdata);

        Body bd = JsonReader.Deserialize<Body> (str);

        Debug.Log (bd.ToString());
    }

}

下面这个只是写个类用于获取路径,(有点多余)

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataPathTest 
 {

    public static string GetDataPath()
    {
        if (Application.platform == RuntimePlatform.IPhonePlayer) {
            string path = Application.dataPath.Substring (0, Application.dataPath.Length - 5);
            return path + "/Dcoument";
        } else if (Application.platform == RuntimePlatform.Android) {
            return Application.persistentDataPath + "/";
        } else {
            return Application.dataPath;
        }
    }
}

     最后补充一个易错的点,就是我起先在用JsonFx转化的时候出现的一些问题,先将body 对象转化为json 字符串,让后在转化为body的过程中出现的报错,后来百度找到了原因,具体可以参考这篇文章:http://www.cnblogs.com/zhuhongjongy/p/4974473.html

今天就写到这里,

待续。。。。

 

Unity游戏开发学习之路——数据持久化

标签:静态   zha   写入   cti   body   conf   win   报错   文件   

原文地址:http://www.cnblogs.com/springword/p/6528173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!