默认计划
2330人加入学习
(3人评价)
【唐老狮】Unity数据持久化之PlayerPrefs
价格 ¥ 99.00
承诺服务
该课程属于 Unity3d实战就业路线课程套餐
请加入后再学习

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

public class SaveDataManager<T> //要跟踪处理所有类,所以必然是个泛型类
{
    Type inputType; //既然要反射,那当然先申明一个Type
    FieldInfo[] fieldInfos;
    T inputObject;
    string keyName;//单个存储名

    void SaveObject()
    {
        PlayerPrefs.SetInt("Var Numbers", fieldInfos.Length);//存数组数量

        for (int i = 0; i < fieldInfos.Length; i++)//浏览fieldInfos数组存储
        {
            //inputType.Name是类名
            //fieldInfos[i].Name是变量名
            //fieldInfos[i].FieldType得到变量类型
            //fieldInfos[i].GetValue(inputObject) 将得到传进来的东西的这里面的变量是什么
            //Convert.ToInt32等强转object

            #region 基本变量存档
            if (fieldInfos[i].FieldType.IsAssignableFrom(typeof(int)))
            {
                PlayerPrefs.SetInt(keyName + "_" + inputType.Name + "_" + fieldInfos[i].Name, 
                                   Convert.ToInt32(fieldInfos[i].GetValue(inputObject)));
            }

            if (fieldInfos[i].FieldType.IsAssignableFrom(typeof(float)))
            {
                PlayerPrefs.SetFloat(keyName + "_" + inputType.Name + "_" + fieldInfos[i].Name,
                                     Convert.ToSingle(fieldInfos[i].GetValue(inputObject)));
            }

            if (fieldInfos[i].FieldType.IsAssignableFrom(typeof(string)))
            {
                PlayerPrefs.SetString(keyName + "_" + inputType.Name + "_" + fieldInfos[i].Name,
                                      Convert.ToString(fieldInfos[i].GetValue(inputObject)));
            }
            #endregion
        }
    }

    void LoadObject(string keyName, T value) //传一个类名同时传一个key名来读取
    {
        inputObject = value;//传进来存起来
        inputType = value.GetType();//我们要得到他的类型
        //然后得到所有公共变量数组
        fieldInfos = inputType.GetFields();

        int varNum = PlayerPrefs.GetInt("Var Numbers");//读数组数量

        object loadObj = Activator.CreateInstance(inputType);//快速构造一个这个类的object变量,类似于new一个

        for (int i = 0; i < varNum; i++)//基于要读档的类里面的变量类型进行读取
        {
            FieldInfo nowVar = inputType.GetField(fieldInfos[i].Name);//得到名字对应新建变量(object)

            #region 基本变量读档
            if (fieldInfos[i].FieldType.IsAssignableFrom(typeof(int)))
                nowVar.SetValue(loadObj, PlayerPrefs.GetInt(keyName + "_" + inputType.Name + "_" + fieldInfos[i].Name));

            if (fieldInfos[i].FieldType.IsAssignableFrom(typeof(float)))
                nowVar.SetValue(loadObj, PlayerPrefs.GetFloat(keyName + "_" + inputType.Name + "_" + fieldInfos[i].Name));

            if (fieldInfos[i].FieldType.IsAssignableFrom(typeof(string)))
                nowVar.SetValue(loadObj, PlayerPrefs.GetString(keyName + "_" + inputType.Name + "_" + fieldInfos[i].Name));
            #endregion
        }
    }
}

[展开全文]

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

public class Player : MonoBehaviour
{
    string keyName;
    string playerName;
    int playerAge;
    int playerAtk;
    int playerDef;
    List<Equipment> equip;


    void SaveMessage()
    {
        PlayerPrefs.SetString(keyName + "Player's Name", playerName);
        PlayerPrefs.SetInt(keyName + "Player's Age", playerAge);
        PlayerPrefs.SetInt(keyName + "Player's Atk", playerAtk);
        PlayerPrefs.SetInt(keyName + "Player's Def", playerDef);

        PlayerPrefs.SetInt(keyName + "Equipment's Count", equip.Count);//存物品数量

        for (int i = 0; i < equip.Count; i++)
        {
            PlayerPrefs.SetInt(keyName + i + "Equipment's id", equip[i].id);
            PlayerPrefs.SetInt(keyName + i + "Equipment's Atk", equip[i].atk);
            PlayerPrefs.SetInt(keyName + i + "Equipment's Def", equip[i].def);
            PlayerPrefs.SetInt(keyName + i + "Equipment's Weight", equip[i].weight);//分 数字 存
        }


        PlayerPrefs.Save();
    }

    void LoadMessage(string keyName)
    {
        this.keyName = keyName;


        playerName = PlayerPrefs.GetString(this.keyName + "Player's Name");
        playerAge = PlayerPrefs.GetInt(this.keyName + "Player's Age");
        playerAtk = PlayerPrefs.GetInt(this.keyName + "Player's Atk");
        playerDef = PlayerPrefs.GetInt(this.keyName + "Player's Def");

        int num = PlayerPrefs.GetInt(this.keyName + "Equipment's Count");//得到有多少个数据
        equip = new List<Equipment>();//初始化容器

        Equipment equipment;
        for (int i = 0; i < num; i++)
        {
            equipment = new Equipment();
            equipment.id = PlayerPrefs.GetInt(this.keyName + i + "Equipment's id");
            equipment.atk = PlayerPrefs.GetInt(this.keyName + i + "Equipment's Atk");
            equipment.def = PlayerPrefs.GetInt(this.keyName + i + "Equipment's Def");
            equipment.weight = PlayerPrefs.GetInt(this.keyName + i + "Equipment's Weight");//将 数字 解包
            equip.Add(equipment);
        }
    }
}

———————————————————

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

public class RankInfo :IComparable<RankInfo> //单条信息
{
    public string playerName;
    public float completeTimes;
    public int totalScroll;

    public RankInfo(string name ,float time,int scroll) //构造方法
    {
        playerName = name;
        completeTimes = time;
        totalScroll = scroll;
    }

    public int CompareTo(RankInfo other)
    {
        if (this.totalScroll >= other.totalScroll) return 1;
        else return -1;
    }
}

public class RankingList
{
    List<RankInfo> rankingList;

    public void AddNewRank(string name, float time ,int scroll)//传新数据进来
    {
        rankingList.Add(new RankInfo(name, time, scroll));//直接加
        rankingList.Sort();
    }


    public void SaveRankingList()
    {
        PlayerPrefs.SetInt("RankingList Num", rankingList.Count);

        for (int i = 0; i < rankingList.Count; i++)
        {
            PlayerPrefs.SetString(i + "RankingList Name", rankingList[i].playerName);
            PlayerPrefs.SetFloat(i + "RankingList Time", rankingList[i].completeTimes);
            PlayerPrefs.SetInt(i + "RankingList Scroll", rankingList[i].totalScroll);
        }
    }

    public void LoadRankingList()
    {
        rankingList = new List<RankInfo>();
        int rankingListCount = PlayerPrefs.GetInt("RankingList Num");

        for (int i = 0; i < rankingListCount; i++)
        {
            string name = PlayerPrefs.GetString(i + "RankingList Name");
            float time = PlayerPrefs.GetFloat(i + "RankingList Time");
            int scroll  = PlayerPrefs.GetInt(i + "RankingList Scroll");

            AddNewRank(name, time, scroll);
        }
    }
}
 

[展开全文]

public class Player : MonoBehaviour, IComparable<Player>
{
    string playerName;
    int playerAge;
    int playerAtk;
    int playerDef;
    int playerScole;
    float compeleteTime;
    List<Player> players;
    List<Equipment> equip;
    List<Player> rankingList;

    public int CompareTo(Player other)
    {
        if (this.playerScole >= other.playerScole) return 1;
        else return -1;
    }

    void SavePlayers()
    {
        PlayerPrefs.SetInt("Player's Count", players.Count);
        for (int i = 0; i < players.Count; i++)
        {
            PlayerPrefs.SetString(i + "Player's Name", playerName);
            PlayerPrefs.SetInt(i + "Player's Age", playerAge);
            PlayerPrefs.SetInt(i + "Player's Atk", playerAtk);
            PlayerPrefs.SetInt(i + "Player's Def", playerDef);

            PlayerPrefs.SetInt("Equipment's Count", equip.Count);//存物品数量

            for (int j = 0; j < equip.Count; j++)
            {
                PlayerPrefs.SetInt(i + j + "Equipment's id", equip[j].id);
                PlayerPrefs.SetInt(i + j + "Equipment's Atk", equip[j].atk);
                PlayerPrefs.SetInt(i + j + "Equipment's Def", equip[j].def);
                PlayerPrefs.SetInt(i + j + "Equipment's Weight", equip[j].weight);//分 数字 存
            }
        }

        PlayerPrefs.Save();
    }

    private void LoadPlayers()
    {
        players = new List<Player>();
        int playersNum = PlayerPrefs.GetInt("Player's Count");

        Player player = new Player();

        for (int i = 0; i < playersNum; i++)
        {
            player.playerName = PlayerPrefs.GetString(i + "Player's Name");
            player.playerAge = PlayerPrefs.GetInt(i + "Player's Age");
            player.playerAtk = PlayerPrefs.GetInt(i + "Player's Atk");
            player.playerDef = PlayerPrefs.GetInt(i + "Player's Def");

            equip = new List<Equipment>();
            Equipment equipment = new Equipment();
            int equipmentNum = PlayerPrefs.GetInt("Equipment's Count");
            for (int j = 0; j < equipmentNum; j++)
            {
                equipment = new Equipment();
                equipment.id = PlayerPrefs.GetInt(i + j + "Equipment's id");
                equipment.atk = PlayerPrefs.GetInt(i + j + "Equipment's Atk");
                equipment.def = PlayerPrefs.GetInt(i + j + "Equipment's Def");
                equipment.weight = PlayerPrefs.GetInt(i + j + "Equipment's Weight");//将 数字 解包
                equip.Add(equipment);
            }
            players.Add(player);
        }
    }

    void SaveRankingList()
    {
        PlayerPrefs.SetInt("rankingListNum", rankingList.Count);

        for (int i = 0; i < rankingList.Count; i++)
        {
            PlayerPrefs.SetString(i + "RankingList Name",playerName);
            PlayerPrefs.SetFloat(i + "RankingList Time", compeleteTime);
            PlayerPrefs.SetInt(i + "RankingList Scole", playerScole);
        }

        PlayerPrefs.Save();
    }

    void LoadRankingList()
    {
        rankingList = new List<Player>();
        int rankingListNum = PlayerPrefs.GetInt("rankingListNum");

        Player player= new Player();

        for (int i = 0; i < rankingListNum; i++)
        {
            player.playerName = PlayerPrefs.GetString(i + "RankingList Name");
            player.compeleteTime = PlayerPrefs.GetFloat(i + "RankingList Time");
            player.playerScole = PlayerPrefs.GetInt(i + "RankingList Scole");
            rankingList.Add(player);
        }

        rankingList.Sort();
    }

    void SaveMessage()
    {
        PlayerPrefs.SetString("Player's Name", playerName);
        PlayerPrefs.SetInt("Player's Age", playerAge);
        PlayerPrefs.SetInt("Player's Atk", playerAtk);
        PlayerPrefs.SetInt("Player's Def", playerDef);

        PlayerPrefs.SetInt("Equipment's Count", equip.Count);//存物品数量

        for (int i = 0; i < equip.Count; i++)
        {
            PlayerPrefs.SetInt(i + "Equipment's id", equip[i].id);
            PlayerPrefs.SetInt(i + "Equipment's Atk", equip[i].atk);
            PlayerPrefs.SetInt(i + "Equipment's Def", equip[i].def);
            PlayerPrefs.SetInt(i + "Equipment's Weight", equip[i].weight);//分 数字 存
        }


        PlayerPrefs.Save();
    }

    void LoadMessage()
    {
        playerName = PlayerPrefs.GetString("Player's Name");
        playerAge = PlayerPrefs.GetInt("Player's Age");
        playerAtk = PlayerPrefs.GetInt("Player's Atk");
        playerDef = PlayerPrefs.GetInt("Player's Def");

        int num = PlayerPrefs.GetInt("Equipment's Count");//得到有多少个数据
        equip = new List<Equipment>();//初始化容器

        Equipment equipment;
        for (int i = 0; i < num; i++)
        {
            equipment = new Equipment();
            equipment.id = PlayerPrefs.GetInt(i + "Equipment's id");
            equipment.atk = PlayerPrefs.GetInt(i + "Equipment's Atk");
            equipment.def = PlayerPrefs.GetInt(i + "Equipment's Def");
            equipment.weight = PlayerPrefs.GetInt(i + "Equipment's Weight");//将 数字 解包
            equip.Add(equipment);
        }
    }
}

[展开全文]

public class Player : MonoBehaviour
{
    string playerName;
    int playerAge;
    int playerAtk;
    int playerDef;
    List<Equipment> equip = new List<Equipment>();

    void SaveMessage()
    {
        PlayerPrefs.SetString("Player's Name", playerName);
        PlayerPrefs.SetInt("Player's Age", playerAge);
        PlayerPrefs.SetInt("Player's Atk", playerAtk);
        PlayerPrefs.SetInt("Player's Def", playerDef);

        PlayerPrefs.SetInt("Equipment's Count", equip.Count);//存物品数量

        for (int i = 0; i < equip.Count; i++)
        {
            PlayerPrefs.SetInt(i + "Equipment's id", equip[i].id);
            PlayerPrefs.SetInt(i + "Equipment's Atk", equip[i].atk);
            PlayerPrefs.SetInt(i + "Equipment's Def", equip[i].def);
            PlayerPrefs.SetInt(i + "Equipment's Weight", equip[i].weight);//分 数字 存
        }


        PlayerPrefs.Save();
    }

    void LoadMessage()
    {
        playerName = PlayerPrefs.GetString("Player's Name");
        playerAge = PlayerPrefs.GetInt("Player's Age");
        playerAtk = PlayerPrefs.GetInt("Player's Atk");
        playerDef = PlayerPrefs.GetInt("Player's Def");

        int num = PlayerPrefs.GetInt("Equipment's Count");//得到有多少个数据
        equip = new List<Equipment>();//初始化容器

        Equipment equipment;
        for (int i = 0; i < num; i++)
        {
            equipment = new Equipment();
            equipment.id = PlayerPrefs.GetInt(i + "Equipment's id");
            equipment.atk = PlayerPrefs.GetInt(i + "Equipment's Atk");
            equipment.def = PlayerPrefs.GetInt(i + "Equipment's Def");
            equipment.weight = PlayerPrefs.GetInt(i + "Equipment's Weight", equip[i].weight);//将 数字 解包
        }
    }

}

[展开全文]

playerprefs  unity提供的数据存储方式

[展开全文]

#region 知识点一PlayerPrefs是什么
//是Unity提供的可以用于存储读取玩家数据的公共类#endregion


#region知识点二存储相关
//PlayerPrefs的数据存储类似于键值对存储一个键对应一个值//提供了存储3种数据的方法int float string
//键:string类型
//值: int float string 对应3种APr#endregion
 

//直接调用set相关方法只会把数据存到内存里

//当游戏结束时unity会自动把数据存到硬盘中
//如果游戏不是正常结束的而是崩溃数据是不会存到硬盘中的

//只要调用该方法就会马上存储到硬盘中
PlayerPrefs.Save();
//PlayerPrefs是有局限性的它只能存3种类型的数据
//如果你想要存储别的类型的数据只能降低精度或者上升精度来进行存储
 

 

#region知识点三读取相关
//注意运行时只要你set了对应键值对//即使你没有马上存储save在本地
//也能够读取出信息
 

[展开全文]

判断某个变量是不是List类型:

typeof(IList).IsAssignableFrom(value.GetType())

 

IsAssignableFrom用于判断父子关系

[展开全文]

FieldInfo info;

通过info.FieldType.Name可以获得字段类型

通过info.Name可以获得字段名

 

重点:判断变量类型:

Type fieldType = value.GetType();

 

if(fieldType == typeof(int))

[展开全文]

1、反射相关

Type——用于获取,类的所有信息,字段,属性,方法等等

Assembly——用于获取程序集,通过程序集获取Type

Activator——用于快速实例化对象

 

2、判断一个类型的对象是否可以让另一个类型为自己分配空间

父类装子类,是否可以从某一个类型的对象,为自己分配空间

Type fatherType = typeof(Father)

Type sonType = typeof(Son)

// 调用者通过该方法判断是否可以通过传入的类型为自己分配空间

if (fatherType.IsAssignableFrom(sonType)){

print("Is ok.");

Father f= Activator.CreateInstance(sonType) as Father;

print(f);   // 输出子类的类名

}

 

3、通过反射获取泛型类型

List<string> list = new List<string>();

// 得到对象的type信息,包括类名与泛型类型

Type listType = list.GetType();

// 得到具体的泛型类型

Type[] types = listType.getGenericArguments();

print(types[0]);   // string

Dictionary<string, float> dic= new Dictionary<string, float>();

Type dicType = dic.GetType();

Type[] types = dicType.getGenericArguments();

print(types[0]);  // string

print(types[1]);  // single

[展开全文]

PlayerPrefs存储位置

1、PlayerPrefs存储的数据存在哪里

 

2、PalyerPrefs数据唯一性

[展开全文]

PlayerPrefs

概念:Unity提供的可用于存储和读取玩家数据的公共类。

存储方式:键值对(键:string,值:int float string)

存储相关方法

注意:

1)这三种set方法只会将数据存储到内存中(但一存后就能进行读取),只有当游戏结束,Unity才会自动将数据存到硬盘里。所以如果游戏不是正常结束,而是崩溃报错结束等,数据会丢失。为了防止这种情况,可以用Save()方法,将数据立即存到硬盘中:

2)因为只有三种值,所以如果想存其他类型的值,只能转换,精度会丢失。使用三目运算符存bool值的一种方法:

3)不同类型使用同一键名进行存储也会覆盖

读取相关方法

三种get方法,传入键名,得到对应值。还有重载,可设定找不到对应值时返回默认值(没设默认值时则取数据类型的默认值,比如int默认为0),即可用来进行基础数据的初始化:

扩展:判断数据是否存在(主要还是用来判断以避免重名):

 删除数据

 

[展开全文]

数据持久化

简单说,即为了避免游戏退出后数据的丢失,而进行的游戏数据的“存盘”和之后的“读盘”。

学习目录:PlayerPrefs、XML、JSON、2进制

[展开全文]

反射3剑客

Type  用于获取类的所有信息,字段,属性,方法

Assembly  用于获取程序集,通过程序集获取Type

Activator  用于快速实例化对象

 

判断一个类型的对象是否可以让另一个类型为自己分配控件

父类装子类

IsAssignableFrom()

 

通过反射获取泛型类型

 

[展开全文]

存储多个玩家数据

只要通过改变key

[展开全文]

PlayerPrefs存储的数据存在哪里?

Windows   

[展开全文]

PlayerPrefs是Unity提供的可以用于存储读取玩家数据的公共类

 

PlayerPrefs的数据存储类似于键值对存储,一个键对应一个值

提供了存储3种数据的方法,int,float,string

键:string类型

值:int float string 对应3种API

存到内存中   PlayerPrefs.SetInt(键,值); 

当游戏结束时,unity回自动把数据存到硬盘中

如果游戏不是正常结束的,而是崩溃,数据不会存到硬盘中

PlayerPrefs.Save();  调用该方法,就会马上存储到硬盘中

PlayerPrefs是有局限性的,它只能存3中类型的数据,如果想要存储其他类型数据,只能降低精度或者上升精度来进行存储

注意:如果不同类型用同一键名进行存储,会进行覆盖

 

读取数据

int xxx = PlayerPrefs.GetInt(键);

如果找不到键对应的值,就会返回函数的第二个参数默值

int xxx = PlayerPrefs.GetInt(键,值);

 

判断数据是否存在

PlayerPrefs.HasKey(键)   

 

删除数据指定键值对

PlayerPrefs.DeleteKey(键);

删除所有储存的信息

PlayerPrefs.DeleteAll();

 

[展开全文]

PlayerPrefs.HasKey 存储时确认是否存在该键以免覆盖

[展开全文]

授课教师

游戏开发前端主程

课程特色

视频(19)
下载资料(13)

学员动态

Clmxk 加入学习
3083725641 加入学习
fengshenzyc 加入学习
icytail 加入学习
猫小叔 加入学习