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

盘子脸在制作单机游戏的时候,先以为没有好多数据需要保存本地. 就没有使用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);

效果图:

image

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