1.5 Unity中的数据存储 PlayerPrefs、XML、JSON

Unity中的三种数据存储:数据存储也称为数据持久化

一、PlayerPrefs

PlayerPrefs是Unity引擎自身提供的一个用于本地持久化保存与读取的类,以键值对的形式将数据保存在文件中,然后程序可以根据关键字提取数值。

PlayerPrefs类支持3种数据类型的保存和读取:浮点型、整形、字符串型

1.保存数据

cs 复制代码
        //保存整型数据
        PlayerPrefs.SetInt("int1",123);
        //保存浮点型数据
        PlayerPrefs.SetFloat("float1",123.4f);
        //保存字符串型数据
        PlayerPrefs.SetString("string1","名字");

2.读取数据

cs 复制代码
        //读取整数型数据
        PlayerPrefs.GetInt("int1");
        //读取浮点型数据
        PlayerPrefs.GetFloat("float1");
        //读取字符串型数据
        PlayerPrefs.GetString("string1");

3.获取数据

通过Key值获取在本地持久化的数据,如果Key值不存在,那么就会返回一个默认值

cs 复制代码
        //读取整数型数据,如果key值不存在 那么就会返回一个默认值0
        PlayerPrefs.GetInt("int1",123);
        //读取浮点型数据,如果key值不存在 那么就会返回一个默认值0.0
        PlayerPrefs.GetFloat("float1",123.4f);
        //读取字符串型数据,如果key值不存在 那么就会返回一个默认值""
        PlayerPrefs.GetString("string1","名字");

4.查找是否存在该键值

cs 复制代码
PlayerPrefs.HasKey("int");

5.清除所有记录

cs 复制代码
 PlayerPrefs.DeleteAll();

6.删除其中某一条记录

cs 复制代码
PlayerPrefs.DeleteKey("int");

7.将记录写入磁盘

cs 复制代码
PlayerPrefs.Save()

8.示例

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PlayerPabsTest : MonoBehaviour
{
 
    // Use this for initialization
    void Start () {
        //写入姓名数据
        PlayerPrefs.SetString("姓名","张三");
        //查找是否存在键值为'姓名'的数据
        if (PlayerPrefs.HasKey("姓名"))
        {
            //读取键值为 '姓名' 的数据 并打印
            Debug.Log(PlayerPrefs.GetString("姓名"));
        }
    }
}

打印结果:

cs 复制代码
张三

9.不同平台的PlayerPrefs存储路径

  • Mac OS X:~/Library/Preferences
  • Windows:HKCU\Software[company name][product name]
  • Linux:~/.config/unity3d/ [CompanyName]/ [ProductName]
  • Windows Store Apps: %userprofile% AppData Local\Packages\[ProductPackageld]>/LocalSt ate/playerprefs.dat
  • WebPlayer
    • Mac OS X: ~/Library/ Preferences/Unity/ WebPlayer Prefs
    • Windows: %APPDATA% Unity\WebPlayer Prefs

10.优缺点

  • 优点:可以快速便捷的处理一些数据,比XMLQ、JSON等其他方法要快的多,对于开发者来说,读写也非常简单
  • 缺点:只能对整数型、浮点型和字符串型三种类型数据进行处理,如果遇上非常庞大的一个数据量就会非常麻烦不利于管理

在开发平时的一些小项目对数据存储功能没有强的需求时,使用效果很好!

注意:PlayerPrfs不同数据,不能同名,即便是不同的数据类型

相关推荐
萘柰奈4 小时前
Unity进阶--C#补充知识点--【Unity跨平台的原理】Mono与IL2CPP
unity·c#·游戏引擎
淡海水5 小时前
【原理】Unity GC 对比 C# GC
unity·c#·gc·垃圾回收
阿赵3D7 小时前
Unity引擎播放HLS自适应码率流媒体视频
unity·游戏引擎·音视频·流媒体·hls
NRatel10 小时前
Unity 游戏提升 Android TargetVersion 相关记录
android·游戏·unity·提升版本
郝学胜-神的一滴11 小时前
Three.js 材质系统深度解析
javascript·3d·游戏引擎·webgl·材质
SmalBox12 小时前
【渲染流水线】[光栅阶段]-[片元着色]以UnityURP为例
unity·渲染
★YUI★1 天前
学习游戏制作记录(玩家掉落系统,删除物品功能和独特物品)8.17
java·学习·游戏·unity·c#
SmalBox1 天前
【渲染流水线】[光栅阶段]-[光栅插值]以UnityURP为例
unity·渲染
谷宇.1 天前
【Unity3D实例-功能-拔枪】角色拔枪(二)分割上身和下身
游戏·unity·c#·游戏程序·unity3d·游戏开发·游戏编程
阿华的代码王国2 天前
【Android】适配器与外部事件的交互
android·xml·java·前端·后端·交互