unity---存档方法PlayerPrefs
存档方法
PlayerPrefs
利用键值对的存储方式
存值的方法: PlayerPrefs.SetString("Name",t);//SetInt,SetFloat
取值的方法: PlayerPrefs.GetString("Name","无");//GetInt,GetFloat 第二个参数为默认值
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextTest : MonoBehaviour
{
// Start is called before the first frame update
public Text text;
public InputField ifd;
public void Submit(){//提交(保存)
string t= ifd.text.ToString();
PlayerPrefs.SetString("Name",t);
}
public void Delete(){//删除
if(PlayerPrefs.HasKey("Name")){
PlayerPrefs.DeleteKey("Name");
}
//删除所有键
// PlayerPrefs.DeleteAll();
}
public void UpLoad(){//上传
text.text=PlayerPrefs.GetString("Name","无");
}
}
利用PlayerPrefs存储复杂结构
需要提前将类通过[System.Serializable]序列化,然后通过 Unity 内部 JsonUtility.Tojson 转化
为 json 字符串,然后再通过PlayerPrefs存储。这部分内容在《Unity3D 游戏开发》P239 有详细介绍。
[System.Serializable]
public class PlayerInfo //用户信息表
{
public string name;
public int score;
public string time;
public PlayerInfo(string name, int score, string time)
{
this.name = name;
this.score = score;
this.time = time;
}
}
[System.Serializable]
public class Record
{
public List<PlayerInfo> RankList;
}
//-----获取/创建
public void Init()
{
if (PlayerPrefs.HasKey("RankList"))
{
record = JsonUtility.FromJson<Record>(PlayerPrefs.GetString("RankList"));
}
else
{
record = new Record();
record.RankList = new List<PlayerInfo>();
}
}
//-----保存
public void SaveRank()
{
string json = JsonUtility.ToJson(record);
PlayerPrefs.SetString("RankList", json);
}