Unity(四十三):存档、文本文件读写
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/StreamingAssetsstring 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-Demostring 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_EDITORif (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/";#elsereturn 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){// 判断字典中是否村在目标keyreturn 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]);}}
}
Unity(四十三):存档、文本文件读写相关推荐
- Android开发笔记(三十三)文本文件和图片文件的读写
文本文件读写 简单文件读写一般是借助于FileOutputStream和FileInputStream,其中FileOutputStream用于写文件,而FileInputStream用于读文件. 写 ...
- 【正点原子Linux连载】第四十三章 Linux设备树 -摘自【正点原子】I.MX6U嵌入式Linux驱动开发指南V1.0
1)实验平台:正点原子阿尔法Linux开发板 2)平台购买地址:https://item.taobao.com/item.htm?id=603672744434 2)全套实验源码+手册+视频下载地址: ...
- OpenCV学习笔记(四十一)——再看基础数据结构core OpenCV学习笔记(四十二)——Mat数据操作之普通青年、文艺青年、暴力青年 OpenCV学习笔记(四十三)——存取像素值操作汇总co
OpenCV学习笔记(四十一)--再看基础数据结构core 记得我在OpenCV学习笔记(四)--新版本的数据结构core里面讲过新版本的数据结构了,可是我再看这部分的时候,我发现我当时实在是看得太马 ...
- 【正点原子MP157连载】第四十三章 外置RTC芯片PCF8563实验-摘自【正点原子】STM32MP1嵌入式Linux驱动开发指南V1.7
1)实验平台:正点原子STM32MP157开发板 2)购买链接:https://item.taobao.com/item.htm?&id=629270721801 3)全套实验源码+手册+视频 ...
- 计算机专业用移动硬盘,评测 篇四十三:国产之光,看这款可做移动硬盘又可系统盘的Orico SSD...
评测 篇四十三:国产之光,看这款可做移动硬盘又可系统盘的Orico SSD 2020-03-22 21:26:50 5点赞 7收藏 17评论 移动存储一直是我们生活中的热门话题,在伴随最近几年的云盘不 ...
- Unity中游戏存档方式
##游戏存档 ####在Unity中游戏存档有如下四种方式: PlayerPrefs c#序列化 XML序列化 Json **原文链接:**http://blog.csdn.net/a23765363 ...
- 作业:文件排版(文本文件读写)
[问题描述] 英文电影中参演人员名单一般以某种方式进行排版显示.给定一个未排版的文件listin.txt,该文件中每行参演人员名单由冒号ldquo:rdquo分隔成前后两部分,但格式杂乱无章,单词(由 ...
- 【正点原子FPGA连载】第四十三章MT9V034摄像头RGB-LCD显示实验 -摘自【正点原子】新起点之FPGA开发指南_V2.1
1)实验平台:正点原子新起点V2开发板 2)平台购买地址:https://detail.tmall.com/item.htm?id=609758951113 2)全套实验源码+手册+视频下载地址:ht ...
- SD卡实验_STM32F1开发指南_第四十三章
第四十三章 SD卡实验 序言: 战舰STM32F103自带了标准的SD卡接口,使用STM3 ...
最新文章
- 68款大规模机器学习数据集,涵盖CV、语音、NLP | 十年资源集
- OSChina 技术周刊第二十九期 —— HTTP 有时候比 HTTPS 好?
- python教程下载地址-最新python实战教程网盘下载地址
- 这就是搜索引擎:核心技术详解
- lightoj 1044 - Palindrome Partitioning(需要优化的区间dp)
- EMLOG复制网站文字提醒弹窗源码美化版
- Visual Studio 2008添加ActiveX控件测试容器(windows 7可用)
- 直线旋转动画html5,多视角3D可旋转的HTML5 Logo动画
- 企业发文的红头文件_【红头文件写作格式】 公司红头文件格式范本
- GetTickCount() 函数的作用和用法
- vs2012c语言参考手册,visualstudio2012教程
- DP1363F国产NFC射频前端芯片替代CLRC663/RC522
- 【三维点云滤波】对三维点云空间数据进行滤波的matlab仿真
- 查询中接受的主体参数
- kubernetes系列之一:Kubernetes如何利用iptables对外暴露service
- 求最小公倍数(扩展版)
- 旋转变换,变换后改变图片大小
- java图书管理系统这个怎么改呢
- Python学习八:pip 最常用命令、pip升级、pip 清华大学开源软件镜像站、Python日期和时间(Time模块、日历(Calendar)模块)
- linux网桥--简介
热门文章
- 利用Verilog计算IQ信号相位的一种方法
- 金融专业术语之——信用转换+期限转换+流动性转换
- 计算机组成原理-中央处理器(CPU基本结构及功能、指令执行、数据通路、硬布线控制器、微程序控制器、指令流水线)
- 调试经验——使用VBA显示Excel中所有faceId对应的图标 (Display all FaceID Icons in Excel with VBA)
- Linux PPP 实现源码分析
- MDD 建模驱动设计
- c++语言程序设计(第四版)郑莉链表的实现源码
- latex subfigure重新编号
- GWAS-性状间相关性图的绘制
- 小满OKKICRM与金蝶云星空对接集成客户档案