Unity-Data Persistence-PlayerPrefs

1. The concept of data persistence

        Data persistence is a collective term for converting an in-memory data model to a storage model, and converting a storage model to an in-memory data model.

        To put it simply: it is to store the game data to the hard disk, and read the data from the hard disk to the game, which is the traditional save.

        It is a public class provided by Unity that can be used to store and read player data.

Two, PlayerPrefs

(1) Basic method of PlayerPrefs

1. Storage related

The data storage of PlayerPrefs is similar to key-value pair storage, where a key corresponds to a value

Provides the method of storing data in 3 int float string

key: string type

Value: int float string corresponding to 3 APIs

direct

PlayerPrefs.SetInt("myAge", 18);//store in memory
PlayerPrefs.SetFloat("myHeight", 229.5f);
PlayerPrefs.SetString("myName", "Yao Ming");

Calling Set related methods directly will only store data in memory

When the game ends, Unity will automatically save the data to the hard disk

If the game crashes with an error, the data will not be saved to the hard disk

PlayerPrefs.Save();

Call this method, it will be stored in the hard disk immediately

 Limitations: Only 3 types of data can be stored

If you want to store others, you can only reduce the precision to store

Boolean type

bool sex = true;

PlayerPrefs.SetInt("sex" , sex ?  1  :  0);

If the type is stored with the same key name, it will be overwritten

PlayerPrefs.SetFloat("myAge",20.2f);

2. Read related

At runtime, as long as the Set corresponds to a key-value pair, the information can be read even if it is not saved to the local immediately

int age = PlayerPrefs.GetInt("myAge");//If not found, return the default value 0

age = PlayerPrefs.GetInt("myAge"  , 100 );

If the value corresponding to myAge cannot be found, the default value of the second parameter of the function will be returned

float height = PlayerPrefs.GetFloat("myHeight" , 1000f);

float name= PlayerPrefs.GetString("myname" , "姚明");

Determine whether the data exists

PlayerPrefs.HasKey("myName");

3. Delete data

Delete the specified key-value pair

PlayerPrefs.DeleteKey();

 delete all stored information

PlayerPrefs.DeleteAll();

4. Exercise 1

 Now there is a player information class, with members such as name, age, attack power, and defense power. There is also an equipment information class. There are two members in the equipment class: id and quantity.
Now encapsulate two methods for it, one is used to store data, and the other is used to read data
Note that the equipment is a list, so it needs to be traversed when storing

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

public class Item
{
    public int id;
    public int num;
}

public class Player
{
    public string name;
    public int age;
    public int atk;
    public int def;
    //拥有的装备信息
    public List<Item> itemList;

    //这个变量 是一个 存储和读取的一个唯一key标识
    private string keyName;

    /// <summary>
    /// 存储数据
    /// </summary>
    public void Save()
    {
        PlayerPrefs.SetString(keyName +"_name", name);
        PlayerPrefs.SetInt(keyName + "_age", age);
        PlayerPrefs.SetInt(keyName + "_atk", atk);
        PlayerPrefs.SetInt(keyName + "_def", def);
        //存储有多少个装备
        PlayerPrefs.SetInt(keyName + "_ItemNum", itemList.Count);
        for (int i = 0; i < itemList.Count; i++)
        {
            //存储每一个装备的信息
            PlayerPrefs.SetInt(keyName + "_itemID" + i, itemList[i].id);
            PlayerPrefs.SetInt(keyName + "_itemNum" + i, itemList[i].num);
        }

        PlayerPrefs.Save();
    }
    /// <summary>
    /// 读取数据
    /// </summary>
    public void Load(string keyName)
    {
        //记录你传入的标识
        this.keyName = keyName;

        name = PlayerPrefs.GetString(keyName + "_name", "未命名");
        age = PlayerPrefs.GetInt(keyName + "_age", 18);
        atk = PlayerPrefs.GetInt(keyName + "_atk", 10);
        def = PlayerPrefs.GetInt(keyName + "_def", 5);

        //得到有多少个装备
        int num = PlayerPrefs.GetInt(keyName + "_ItemNum", 0);
        //初始化容器
        itemList = new List<Item>();
        Item item;
        for (int i = 0; i < num; i++)
        {
            item = new Item();
            item.id = PlayerPrefs.GetInt(keyName + "_itemID" + i);
            item.num = PlayerPrefs.GetInt(keyName + "_itemNum" + i);
            itemList.Add(item);
        }
    }
}

public class Lesson1_Exercises : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        //现在有玩家信息类,有名字,年龄,攻击力,防御力等成员
        //现在为其封装两个方法,一个用来存储数据,一个用来读取数据

        //Player p = new Player();
        //p.Load();
        //print(p.name);
        //print(p.age);
        //print(p.atk);
        //print(p.def);

        //p.name = "唐老狮";
        //p.age = 22;
        //p.atk = 40;
        //p.def = 10;
        改了过后存储
        //p.Save();

 

        Player p = new Player();
        p.Load("Player1");
        p.Save();

        Player p2 = new Player();
        p2.Load("Player2");
        p.Save();
        //装备信息
        //print(p.itemList.Count);
        //for (int i = 0; i < p.itemList.Count; i++)
        //{
        //    print("道具ID:" + p.itemList[i].id);
        //    print("道具数量:" + p.itemList[i].num);
        //}

        为玩家添加一个装备
        //Item item = new Item();
        //item.id = 1;
        //item.num = 1;
        //p.itemList.Add(item);
        //item = new Item();
        //item.id = 2;
        //item.num = 2;
        //p.itemList.Add(item);

    }

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

 (2) Storage location of PlayerPrefs on different platforms

1. Different platforms have different storage locations

Window

//PlayerPrefs are stored in
the registry under //HKCU\Software\[Company Name]\Product Name]
//where Company and Product Name are the names set in "Project settings".
//Run regedit
//HKEY_CURRENT_USER/ /SOFTWARE
//Unity
//UnityEditor//Company Name//Product Name
 

Android

/data/data/package name/shared_prefs/pkg-name.xml

IOS

/Library/Preferences/[App ID].plist

2. Uniqueness of PlayerPrefs data

//Uniqueness of different data in PlayerPrefs

//It is determined by the key, different keys determine different data

//If different data keys are the same in the same project, data will be lost

// To ensure that the data is not lost, a rule must be established to ensure that the key is unique

3. Exercise 2

To make a leaderboard function in the game, the leaderboard mainly records the player name (repeatable), player score, and player clearance time. Please use PlayerPrefs to store and read the related information of the leaderboard Note: the name can be repeated, which means it cannot be
separated use name as key

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

/// <summary>
/// 排行榜具体信息
/// </summary>
public class RankListInfo
{
    public List<RankInfo> rankList;

    public RankListInfo()
    {
        Load();
    }

    /// <summary>
    /// 新加排行榜信息
    /// </summary>
    public void Add(string name , int score, int time)
    {
        rankList.Add(new RankInfo(name, score, time));
    }

    public void Save()
    {
        //存储有多少条数据
        PlayerPrefs.SetInt("rankListNum", rankList.Count);
        for (int i = 0; i < rankList.Count; i++)
        {
            RankInfo info = rankList[i];
            PlayerPrefs.SetString("rankInfo" + i, info.playerName);
            PlayerPrefs.SetInt("rankScore" + i, info.playerScore);
            PlayerPrefs.SetInt("rankTime" + i, info.playerTime);
        }
    }

    private void Load()
    {
        int num = PlayerPrefs.GetInt("rankListNum", 0);
        rankList = new List<RankInfo>();
        for (int i = 0; i < num; i++)
        {
            RankInfo info = new RankInfo(PlayerPrefs.GetString("rankInfo" + i),
                                          PlayerPrefs.GetInt("rankScore" + i),
                                          PlayerPrefs.GetInt("rankTime" + i));
            rankList.Add(info);
        }
    }
}

/// <summary>
/// 排行榜单条信息
/// </summary>
public class RankInfo
{
    public string playerName;
    public int playerScore;
    public int playerTime;

    public RankInfo(string name, int score, int time)
    {
        playerName = name;
        playerScore = score;
        playerTime = time;
    }
}

public class Lesson2_Exercises : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        #region 练习题一 
        //将知识点一中的练习题,改为可以支持存储多个玩家信息
        #endregion

        #region 练习题二
        //要在游戏中做一个排行榜功能
        //排行榜主要记录玩家名(可重复),玩家得分,玩家通关时间
        //请用PlayerPrefs存储读取排行榜相关信息

        RankListInfo rankList = new RankListInfo();
        print(rankList.rankList.Count);
        for (int i = 0; i < rankList.rankList.Count; i++)
        {
            print("姓名" + rankList.rankList[i].playerName);
            print("分数" + rankList.rankList[i].playerScore);
            print("时间" + rankList.rankList[i].playerTime);
        }

        rankList.Add("唐老狮", 100, 99);
        rankList.Save();
        #endregion
    }

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

 (3) Using reflection combined with PlayerPrefs to make a general storage tool

Guess you like

Origin blog.csdn.net/weixin_53163894/article/details/131493246