在各种游戏中,由于游戏的数据并不是每一个关卡都要初始化,有的场景需要知道上一个场景中的某些数据,并且根据这些数据来调整游戏的场景,因此需要一个类来保存游戏中的数据 ———— PlayerPrfs类
首先要明确的一点就是,PlayerPrfs类记录消息的机制是通过键值对来记录,每一个标识符都有一个值与其对应,不论是储存数据还是提取数据都需要两者协同合作才能进行
类中的方法
SetInt | 将需要记录的整型消息用标识符记录下来 |
---|---|
SetFloat | 浮点类型数据 |
SetString | 字符串数据 |
DeleteKey | 删除标识符 |
HasKey | 是否存在标识符,存在返回true反之返回False |
DeleteAll | 删除全部储存的信息 |
Save | 保存数据 |
GetInt/GetFloat/GetString | 根据标识符获取对应的数据 |
实例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerPrefsDemo : MonoBehaviour
{
/// <summary>
/// PlayerPrefs类的使用方法与详解
/// </summary>
// Start is called before the first frame update
public Button First;/// <summary>
/// 三个button变量
/// </summary>
public Button Second;
public Button Thirdd;
private void Awake()
{
PlayerPrefs.SetInt("Fir", 666);//将666整型数据储存
PlayerPrefs.SetFloat("Sec",0.003f);//储存浮点数据
PlayerPrefs.SetString("Third",WWW.EscapeURL("unity3D实战训练"));///将字符串中包含的中文字符转义
Print();//输出数据
PlayerPrefs.DeleteKey("Fir");//删除类中键值
Check();
PlayerPrefs.HasKey("Fir");
}
void Start()
{
}
private void Print()
{
Debug.Log("First value" + PlayerPrefs.GetInt("Fir"));
}
// Update is called once per frame
void Update()
{
}
private void Check()
{
Debug.Log("Fir's key" + PlayerPrefs.HasKey("Fir"));
Debug.Log("Sec's key" + PlayerPrefs.HasKey("Sec"));
Debug.Log("Third's key" + PlayerPrefs.HasKey("Third"));
}
}