PlayerPrefs(运行模式)
using UnityEngine;
namespace Example_01.Scripts
{
public class GameArchives : MonoBehaviour
{
public string key;
public string nickName = "PLee";
public int age = 25;
public float height = 1.71f;
private void OnGUI()
{
GUILayoutOption[] options =
{
GUILayout.Width(300),
};
GUILayout.Label("【PlayerPrefs】");
GUILayout.Label("键:");
key = GUILayout.TextField(key, 10, options);
GUILayout.Label("昵称:");
nickName = GUILayout.TextField(nickName, 10, options);
GUILayout.Label($"年龄: {
age}");
age = (int)GUILayout.HorizontalSlider(age, 0, 100, options);
GUILayout.Label($"身高: {
height}");
height = GUILayout.HorizontalSlider(height, 1, 2, options);
// 存档
if (GUILayout.Button("存档"))
{
PlayerPrefs.SetString("NickName", nickName);
PlayerPrefs.SetInt("Age", age);
PlayerPrefs.SetFloat("Height", height);
Debug.Log("已存档");
}
// 强制保存数据
if (GUILayout.Button("强制保存数据"))
{
PlayerPrefs.SetString("NickName", nickName);
PlayerPrefs.SetInt("Age", age);
PlayerPrefs.SetFloat("Height", height);
PlayerPrefs.Save(); // 强制保存数据
Debug.Log("强制保存数据");
}
// 读档
if (GUILayout.Button("读档"))
Debug.Log($"{
PlayerPrefs.GetString("NickName")} ---> {
PlayerPrefs.GetInt("Age")} ---> {
PlayerPrefs.GetFloat("Height")}");
// 判断是否存在某个键
if (GUILayout.Button("判断是否存在某个键")) Debug.Log(PlayerPrefs.HasKey(key) ? $"{
key} 存在" : $"{
key} 不存在");
// 删除某个键
if (GUILayout.Button("删档")) PlayerPrefs.DeleteKey(key);
// 删除所有键
if (GUILayout.Button("清空存档")) PlayerPrefs.DeleteAll();
}
}
}
EditorPrefs(编辑器模式)
using Example_01.Scripts;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(GameArchives))]
public class GameArchivesEditor : Editor
{
public override void OnInspectorGUI()
{
GUILayout.Label("【PlayerPrefs】");
base.OnInspectorGUI();
GUILayout.Label("【EditorPrefs】");
GameArchives script = target as GameArchives;
// 存档
if (GUILayout.Button("存档"))
{
EditorPrefs.SetString("NickName", script!.nickName);
EditorPrefs.SetInt("Age", script.age);
EditorPrefs.SetFloat("Height", script.height);
Debug.Log("已存档");
}
// 读档
if (GUILayout.Button("读档"))
Debug.Log($"{
EditorPrefs.GetString("NickName")} ---> {
EditorPrefs.GetInt("Age")} ---> {
EditorPrefs.GetFloat("Height")}");
// 判断是否存在某个键
if (GUILayout.Button("判断是否存在某个键")) Debug.Log(EditorPrefs.HasKey(script!.key) ? $"{
script.key} 存在" : $"{
script.key} 不存在");
// 删除某个键
if (GUILayout.Button("删档")) EditorPrefs.DeleteKey(script!.key);
// 删除所有键
if (GUILayout.Button("清空存档")) EditorPrefs.DeleteAll();
}
}
文本文件读写
编辑器模式
public class ReadWriteTextFileEditor
{
[MenuItem("Tools/Read & Write File")]
public static void ReadWriteText()
{
string path = Path.Combine(Application.dataPath, "test.txt");
if(File.Exists(path)) File.Delete(path);
StringBuilder sb = new StringBuilder();
sb.Append("Prosper").AppendLine();
sb.Append("Lee").AppendLine();
File.WriteAllText(path, sb.ToString());
AssetDatabase.Refresh();
Debug.Log(File.ReadAllText(path));
}
}
运行模式
public class ReadWriteTextFile : MonoBehaviour
{
private void Start()
{
// 可读不可写
string resourcesText = Resources.Load<TextAsset>("test").text;
Debug.Log($"可读不可写 ---> {
resourcesText}");
// 可读不可写
Debug.Log(Application.streamingAssetsPath); // [Project]/Assets/StreamingAssets
string path1 = Path.Combine(Application.streamingAssetsPath, "test.txt");
string streamingAssetsText = File.ReadAllText(path1);
Debug.Log($"可读不可写 ---> {
streamingAssetsText}");
// 可读可写
Debug.Log(Application.persistentDataPath); // C:/Users/[username]/AppData/LocalLow/DefaultCompany/Unity-Example-Demo
string path2 = Path.Combine(Application.persistentDataPath, "test.txt");
File.WriteAllText(path2, DateTime.Now.ToString(CultureInfo.InvariantCulture));
string persistentDataText = File.ReadAllText(path2);
Debug.Log($"可读可写 ---> {
persistentDataText}");
}
private void OnGUI()
{
#if UNITY_EDITOR
if (GUILayout.Button("打开文件夹")) EditorUtility.RevealInFinder(Application.persistentDataPath);
#endif
}
}
利用文件读写增删改查游戏记录
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace Example_01.Scripts
{
public static class RecordUtil
{
// 存储存档文件内容
public static readonly Dictionary<string, string> RecordContent = new Dictionary<string, string>();
// 游戏存档保存的跟目录
// UNITY_STANDALONE 独立的平台 (Mac, Windows or Linux).
public static string RecordRootPath
{
get
{
#if (UNITY_EDITOR || UNITY_STANDALONE)
return Application.dataPath + "/../Record/";
#else
return Application.persistentDataPath + "/Record/";
#endif
}
}
static RecordUtil()
{
// 如果文件夹存在
if (Directory.Exists(RecordRootPath))
{
// SearchOption 用于指定搜索操作是应包含所有子目录还是仅包含当前目录的枚举值之一
// SearchOption.AllDirectories 在搜索操作中包括当前目录和所有它的子目录。 此选项在搜索中包括重解析点,比如安装的驱动器和符号链接
// SearchOption.TopDirectoryOnly 仅在搜索操作中包括当前目录
foreach (string filePath in Directory.GetFiles(RecordRootPath, "*record", SearchOption.TopDirectoryOnly))
{
// 获取文件名(不报换扩展名)
string key = Path.GetFileNameWithoutExtension(filePath);
RecordContent[key] = File.ReadAllText(filePath, new UTF8Encoding(false));
}
}
}
// 存档
public static void Save(string value)
{
try
{
string date = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
RecordContent[date] = value;
string path = Path.Combine(RecordRootPath, $"{
date}.record");
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, value, new UTF8Encoding(false));
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
// 删档
public static void Delete(string key)
{
try
{
RecordContent.Remove(key);
File.Delete(Path.Combine(RecordRootPath, $"{
key}.record"));
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
// 改档
public static void Modify(string key, string value)
{
try
{
RecordContent[key] = value;
string path = Path.Combine(RecordRootPath, $"{
key}.record");
File.WriteAllText(path, value, new UTF8Encoding(false));
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
// 查档
public static string Get(string key)
{
// 判断字典中是否村在目标key
return RecordContent.TryGetValue(key, out string value) ? value : string.Empty;
}
}
}
运行模式
using System.Collections.Generic;
using UnityEngine;
namespace Example_01.Scripts
{
public class Record : MonoBehaviour
{
private int index = 0;
private string content;
private void OnGUI()
{
GUILayout.Label(RecordUtil.RecordRootPath);
Dictionary<string, string> recordContent = RecordUtil.RecordContent;
List<string> recordKeys = new List<string>();
recordKeys.Add("None");
foreach (string key in recordContent.Keys)
{
recordKeys.Add(key);
}
index = GUILayout.SelectionGrid(index, recordKeys.ToArray(), 1);
// index = GUILayout.Popup("存档列表", index, recordKeys.ToArray());
content = GUILayout.TextArea(content);
if (GUILayout.Button("存档"))
{
RecordUtil.Save(content);
}
if (GUILayout.Button("删档"))
{
RecordUtil.Delete(recordKeys[index]);
}
if (GUILayout.Button("改档"))
{
RecordUtil.Modify(recordKeys[index], content);
}
if (GUILayout.Button("查档"))
{
content = RecordUtil.Get(recordKeys[index]);
}
}
}
}
编辑器模式
using System.Collections.Generic;
using Example_01.Scripts;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Record))]
public class RecordEditor : Editor
{
private int index = 0;
private string content;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.LabelField(RecordUtil.RecordRootPath);
Dictionary<string, string> recordContent = RecordUtil.RecordContent;
List<string> recordKeys = new List<string>();
recordKeys.Add("None");
foreach (string key in recordContent.Keys)
{
recordKeys.Add(key);
}
index = EditorGUILayout.Popup("存档列表", index, recordKeys.ToArray());
content = EditorGUILayout.TextArea(content);
if (GUILayout.Button("存档"))
{
RecordUtil.Save(content);
}
if (GUILayout.Button("删档"))
{
RecordUtil.Delete(recordKeys[index]);
}
if (GUILayout.Button("改档"))
{
RecordUtil.Modify(recordKeys[index], content);
}
if (GUILayout.Button("查档"))
{
content = RecordUtil.Get(recordKeys[index]);
}
}
}