本章开始重头编写并讲解保存系统,讲解关于二进制和电脑数据文本存储,学习读取和写入文件。
SavingSystem_X
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using UnityEngine;
-
- namespace RPG.Saving
- {
- //
- public class SavingSystem_X : MonoBehaviour
- {
- public void save(string saveFile)//// 保存游戏状态到指定文件
- {
- string path = GetPathFromSaveFile(saveFile);
- print("存档"+path);
- FileStream stream = File.Open(path, FileMode.Create);
- byte[] bytes = Encoding.UTF8.GetBytes("Hello Shine");
- stream.Write(bytes,0, bytes.Length);
- stream.Close();
- }
-
- public void Load(string saveFile)//// 从指定文件加载游戏状态
- {
- print("加载"+GetPathFromSaveFile(saveFile));
- }
-
- private string GetPathFromSaveFile(string saveFile) // 用于构造保存文件的完整路径
- {
- return Path.Combine(Application.persistentDataPath,saveFile+".sav"); // 结合持久数据路径与给定的保存文件名,并添加 ".sav" 扩展名
- }
- }
- }
-
复制代码
SavingWrapper_X
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- namespace RPG.Saving
- {
- //
- public class SavingWrapper_X : MonoBehaviour
- {
- const string defaultSaveFile = "Save";
-
- private void Update()
- {
- if(Input.GetKeyDown(KeyCode.S))
- {
- GetComponent<SavingSystem_X>().save(defaultSaveFile);
- }
- if(Input.GetKeyDown(KeyCode.L))
- {
- GetComponent<SavingSystem_X>().Load(defaultSaveFile);
- }
- }
-
-
- }
- }
-
复制代码
|