Udemy-Unity制作类暗黑破坏神游戏记录-P84-P88

2024-09-22
180看过
本章开始重头编写并讲解保存系统,讲解关于二进制和电脑数据文本存储,学习读取和写入文件。

SavingSystem_X

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using UnityEngine;
  6. namespace RPG.Saving
  7. {
  8.     //
  9.     public class SavingSystem_X : MonoBehaviour
  10.     {
  11.         public void save(string saveFile)//// 保存游戏状态到指定文件
  12.         {
  13.             string path = GetPathFromSaveFile(saveFile);
  14.             print("存档"+path);
  15.             FileStream stream = File.Open(path, FileMode.Create);
  16.             byte[] bytes = Encoding.UTF8.GetBytes("Hello Shine");
  17.             stream.Write(bytes,0, bytes.Length);
  18.             stream.Close();
  19.         }
  20.         public void Load(string saveFile)//// 从指定文件加载游戏状态
  21.         {
  22.             print("加载"+GetPathFromSaveFile(saveFile));
  23.         }
  24.         private string GetPathFromSaveFile(string saveFile) // 用于构造保存文件的完整路径
  25.         {
  26.             return Path.Combine(Application.persistentDataPath,saveFile+".sav");  // 结合持久数据路径与给定的保存文件名,并添加 ".sav" 扩展名
  27.         }
  28.     }
  29. }
复制代码
SavingWrapper_X

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace RPG.Saving
  5. {
  6.     //
  7.     public class SavingWrapper_X : MonoBehaviour
  8.     {
  9.         const string defaultSaveFile = "Save";
  10.         private void Update()
  11.         {
  12.             if(Input.GetKeyDown(KeyCode.S))
  13.             {
  14.                 GetComponent<SavingSystem_X>().save(defaultSaveFile);
  15.             }
  16.             if(Input.GetKeyDown(KeyCode.L))
  17.             {
  18.                 GetComponent<SavingSystem_X>().Load(defaultSaveFile);
  19.             }
  20.         }
  21.         
  22.     }
  23. }
复制代码
微信图片_20240923104839.png

回复

举报

 
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表