Unity中的PlayerPrefs
,这是一个用于存储小型数据的类,比如玩家的设置、得分、进度等。这些数据会存储在玩家的设备上,即使应用程序关闭后也能保持。
以下是一些关于PlayerPrefs
的基本操作:
1.存储数据:
使用PlayerPrefs.SetString
, PlayerPrefs.SetInt
, 或 PlayerPrefs.SetFloat
等方法可以存储字符串、整数或浮点数。
// 存储一个字符串
PlayerPrefs.SetString("player_name", "Kami");
// 存储一个整数
PlayerPrefs.SetInt("player_score", 1000);
// 存储一个浮点数
PlayerPrefs.SetFloat("player_health", 100.0f);
2.获取数据:
使用PlayerPrefs.GetString
, PlayerPrefs.GetInt
, 或 PlayerPrefs.GetFloat
等方法可以获取之前存储的数据。
// 获取一个字符串
string playerName = PlayerPrefs.GetString("player_name");
// 获取一个整数
int playerScore = PlayerPrefs.GetInt("player_score");
// 获取一个浮点数
float playerHealth = PlayerPrefs.GetFloat("player_health");
3.删除数据: 使用PlayerPrefs.DeleteKey
方法可以删除特定的存储项。
// 删除一个存储项
PlayerPrefs.DeleteKey("player_name");
4.保存数据:
所有的PlayerPrefs
操作都是即时的,但为了确保数据不会因异常退出而丢失,应该在修改数据后调用PlayerPrefs.Save
。
// 保存所有PlayerPrefs数据
PlayerPrefs.Save();
eg:通过持久化数据来实现简易换装
最终实现:最后可以实现在第一个场景切换的服装,在下一场景加载时仍为该服装
(目的:不一定只有对应的类型值才可以进行持久化数据,通过值作为一个标识,来实现不同场景中的 “持久化数据” 的实现。)
场景一:给该模型挂载脚本ChangeClothes,用来实现换装和一个持久化数据的存储。实现后的效果可以给角色切换服装,并存储一个持久化数据,用于下一个场景加载。详细如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
///summary
///换装
///summary
public class ChangeClothes : MonoBehaviour
{
private SkinnedMeshRenderer skinRender;
public Texture[] texture;
private int index=3; //默认服装 没有换装时,默认的服装
void Start()
{
skinRender = GetComponentInChildren<SkinnedMeshRenderer>(); //从子物体获取 本身无该组件
}
void Update()
{
}
private void OnGUI()
{
if (GUILayout.Button("ChangeCloth01"))
{
skinRender.material.mainTexture = texture[0];
index = 0; //标识值的记录 后面同理
//PlayerPrefs.SetInt("ChangeCloth01", index); //换完装之后就存储
}
else if (GUILayout.Button("ChangeCloth02"))
{
skinRender.material.mainTexture = texture[1];
index = 1;
//PlayerPrefs.SetInt("ChangeCloth02", 1);
}
else if (GUILayout.Button("ChangeCloth03"))
{
skinRender.material.mainTexture = texture[2];
index = 2;
//PlayerPrefs.SetInt("ChangeCloth03", index);
}
if (GUILayout.Button("保存并切换下一个场景"))
{
PlayerPrefs.SetInt("cloth", index); //存储数据
SceneManager.LoadScene(1);
}
}
}
场景二:给场景中任何一个物体挂载脚本Brith用来实例化上一个场景的模型。模型作为预制体,自带GetCloth脚本,该脚本用于获取上一场景保存的服装,通过持久化数据获取该服装并加载。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
///summary
///
///summary
public class Brith : MonoBehaviour
{
public GameObject prefab;
private void Start()
{
Instantiate(prefab);
}
private void OnGUI()
{
if (GUILayout.Button("返回上一个场景"))
{
SceneManager.LoadScene(0);
}
}
}
预制体所带脚本:GetCloth
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///summary
///
///summary
public class GetCloth : MonoBehaviour
{
private SkinnedMeshRenderer m_render;
public Texture[] texture; //纹理素材位置要与上一场景对应 最后一个是默认服装 用于上一场景不换装时
void Start()
{
m_render=GetComponentInChildren <SkinnedMeshRenderer>();
if (PlayerPrefs.HasKey("cloth"))
{
m_render.material.mainTexture = texture[PlayerPrefs.GetInt("cloth")];
}
}
}