Unity中的三种数据存储:数据存储也称为数据持久化
PlayerPrefs是Unity引擎自身提供的一个用于本地持久化保存与读取的类,以键值对的形式将数据保存在文件中,然后程序可以根据关键字提取数值。
PlayerPrefs类支持3种数据类型的保存和读取:浮点型、整形、字符串型
//保存整型数据
PlayerPrefs.SetInt("int1",123);
//保存浮点型数据
PlayerPrefs.SetFloat("float1",123.4f);
//保存字符串型数据
PlayerPrefs.SetString("string1","名字");
//读取整数型数据
PlayerPrefs.GetInt("int1");
//读取浮点型数据
PlayerPrefs.GetFloat("float1");
//读取字符串型数据
PlayerPrefs.GetString("string1");
通过Key值获取在本地持久化的数据,如果Key值不存在,那么就会返回一个默认值
//读取整数型数据,如果key值不存在 那么就会返回一个默认值0
PlayerPrefs.GetInt("int1",123);
//读取浮点型数据,如果key值不存在 那么就会返回一个默认值0.0
PlayerPrefs.GetFloat("float1",123.4f);
//读取字符串型数据,如果key值不存在 那么就会返回一个默认值""
PlayerPrefs.GetString("string1","名字");
PlayerPrefs.HasKey("int");
PlayerPrefs.DeleteAll();
PlayerPrefs.DeleteKey("int");
PlayerPrefs.Save()
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("姓名"));
}
}
}
打印结果:
张三
在开发平时的一些小项目对数据存储功能没有强的需求时,使用效果很好!
注意:PlayerPrfs不同数据,不能同名,即便是不同的数据类型