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

Unity PlayerPrefs类进行扩展(整个对象进行保存)

时间:2016-01-30 13:17:32      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

盘子脸在制作单机游戏的时候,先以为没有好多数据需要保存本地. 就没有使用json等格式自己进行保存. 使用PlayerPrefs类,但是后面字段越来越多的时候.

PlayerPrefs保存就发现要手动写很多代码. 于是是否可以写一个辅助方法自动帮我保存一个对象,取出一个对象呢?

代码如何下:

public static class PlayerPrefsExtend 
{
    public static void Save(string objectName,LocalEntityBase o) 
    {
        Type t = o.GetType();
        FieldInfo [] fiedls =  t.GetFields();
        for (int i = 0; i < fiedls.Length; i++)
        {
            string saveName = objectName + "." + o.Identification + "." + fiedls[i].Name;
            switch (fiedls[i].FieldType.Name)
            {
                case "String":
                    PlayerPrefs.SetString(saveName, fiedls[i].GetValue(o).ToString());
                    break;
                case "Int32":
                case "Int64":
                case "Int":
                case "uInt":
                    PlayerPrefs.SetInt(saveName, (int)fiedls[i].GetValue(o));
                    break;
                case "Float":
                    PlayerPrefs.SetFloat(saveName, (float)fiedls[i].GetValue(o));
                    break;
            }
        }
    }


    public static T GetValue<T>(string objectName) where T : LocalEntityBase, new()
    {
        T newObj = new T();

        Type t = newObj.GetType();
        FieldInfo[] fiedls = t.GetFields();
        for (int i = 0; i < fiedls.Length; i++)
        {
            string saveName = objectName + "." + newObj.Identification + "." + fiedls[i].Name;
            switch (fiedls[i].FieldType.Name)
            {
                case "String":
                    fiedls[i].SetValue(newObj,PlayerPrefs.GetString(saveName));
                    break;
                case "Int32":
                case "Int64":
                case "Int":
                case "uInt":
                    fiedls[i].SetValue(newObj, PlayerPrefs.GetInt(saveName));
                    break;
                case "Float":
                    fiedls[i].SetValue(newObj,PlayerPrefs.GetFloat(saveName));
                    break;
            }
        }

        return newObj;
    }
}

操作代码 :

PlayerPrefs.DeleteAll();

User user = new User();
user.Name = "盘子脸";
user.Age = 10;
user.Describe = "码农=。= ";
PlayerPrefsExtend.Save("ID1", user);

user = null;

user = PlayerPrefsExtend.GetValue<User>("ID1");

Debug.Log("user name: " + user.Name);
Debug.Log("user Age: " + user.Age);
Debug.Log("user Describe: " + user.Describe);

//以前的写法,就要手动写很多key.
//PlayerPrefs.SetString("Name", user.Name);
//PlayerPrefs.SetInt("Age", user.Age);
//PlayerPrefs.GetString("Describe", user.Describe);

效果图:

技术分享

Unity PlayerPrefs类进行扩展(整个对象进行保存)

标签:

原文地址:http://www.cnblogs.com/plateFace/p/5170544.html

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