数据持久化-PlayerPrefs

一、基础方法

1、介绍持久化

将内存中的数据存储到硬盘中。

2、PalyerPrefs是一个存储玩家数据的公共类。

3、存储相关

键是唯一的,即使是存储不同类型的。

4、读取相关

取值和其参数介绍:

第二个参数是用来赋予默认值的。并不会存储到硬盘中。

判断是否存在该键:

删除数据

练习题:

第一题 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player1 : MonoBehaviour
{
    public string name;
    public int age;
    public int atk;
    public int def;
    void SaveData()
    {
        PlayerPrefs.SetString("name", this.name);
        PlayerPrefs.SetInt("age", this.age);
        PlayerPrefs.SetInt("atk", this.atk);
        PlayerPrefs.SetInt("def", this.def);
    }

    void ReadData()
    {
        name = PlayerPrefs.GetString("name", "未知名称");
        age = PlayerPrefs.GetInt("age", 20);
        atk = PlayerPrefs.GetInt("atk", 1);
        def = PlayerPrefs.GetInt("def", 1);
        print($"玩家{name}({age}岁)目前攻击力:{age},防御力:{def}");
    }
    private void Start()
    {
        SaveData();
        ReadData();
    }
}

二、存储位置

1、不同平台位置:

windows:

Android:

IOS:

2、保证数据不重复

练习题

PlayerPrefs主要作用

相关推荐
SmalBox1 天前
02-03-原理篇-资源打包流程详解
unity3d·游戏开发
SmalBox2 天前
02-02-原理篇-Unity Addressable Assets原理深度解析
unity3d·游戏开发
_zhourui_h_3 天前
Unity 内存数据极限防护:一个 int 藏 8 份密文,修改器到底还能怎么改?
unity3d
SmalBox3 天前
02-01-原理篇-Unity原生AssetBundle原理深度解析
unity3d·游戏开发
fujisheng6613 天前
FUI 验证实战:从 Prefab 节点改名到生成诊断与构建门禁
unity3d
_zhourui_h_4 天前
Unity AssetBundle 打包极限治理:依赖环、重复资源、包体膨胀,怎么在上线前全部揪出来?
unity3d
_zhourui_h_5 天前
Unity AssetBundle 极限管理:依赖、异步加载、引用计数、自动卸载到底怎么串起来?
unity3d
SmalBox5 天前
01-09-认知篇-对比-方案选型矩阵
unity3d·游戏开发
鑫鑫哥adam6 天前
用一个 struct 给游戏关键数值上锁:ProtectedInt 反作弊实践
unity3d
fujisheng6616 天前
FUI 导航实践:拆开 Layer、History、Coverage 与 Cache 的组合语义
c#·unity3d