Unity类银河战士恶魔城学习总结(P146 Delete Save file-P147 Encryption of save data删除数据和加密数据)

【Unity教程】从0编程制作类银河恶魔城游戏_哔哩哔哩_bilibili

教程源地址:https://www.udemy.com/course/2d-rpg-alexdev/

本章节实现了快速删除存档和加密存档

以下是加密前和加密后的对比

SaveManager.cs

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;



//2024.11.25
public class SaveManager : MonoBehaviour
{
    public static SaveManager instance;

    [SerializeField] private string fileName;
    [SerializeField] private bool encryptData;

    private GameData gameData;
    private List<ISaveManager> saveManagers = new List<ISaveManager>();
    private FileDataHandler dataHandler;


    [ContextMenu("Delete save file")]
    private void DeleteSaveData()
    {
        dataHandler = new FileDataHandler(Application.persistentDataPath, fileName, encryptData);
        dataHandler.Delete();
    }

    private void Awake()
    {
        if (instance != null)
            Destroy(instance.gameObject);
        else
            instance = this;
    }

    private void Start()
    {
        dataHandler = new FileDataHandler(Application.persistentDataPath,fileName, encryptData);
        saveManagers = FindAllSaveManagers();

        LoadGame();
    }


    public void NewGame()
    {
        gameData = new GameData();
    }


    public void LoadGame()
    {
        gameData = dataHandler.Load();

        if (this.gameData == null)
        {
            Debug.Log("没有找到存档");
            NewGame();
        }

        foreach (ISaveManager saveManager in saveManagers)
        {
            saveManager.LoadData(gameData);
        }

        
    }


    public void SaveGame()
    {
        foreach(ISaveManager saveManager in saveManagers)
        {
            saveManager.SaveData(ref gameData);
        }

        dataHandler.Save(gameData);
    }


    private void OnApplicationQuit()
    {
        SaveGame();
    }


    private List<ISaveManager> FindAllSaveManagers()
    {
        IEnumerable<ISaveManager> saveManagers = FindObjectsOfType<MonoBehaviour>(true).OfType<ISaveManager>();

        return new List<ISaveManager>(saveManagers);

    }
}

FileDataHandler.cs

Save 方法

  • 功能:将 GameData 数据保存到指定路径的文件中。
  • 核心逻辑
    1. 创建完整路径 :通过 Path.Combine 组合文件夹路径和文件名。
    2. 确保文件夹存在 :调用 Directory.CreateDirectory 确保路径中的文件夹被创建。
    3. 序列化数据 :使用 JsonUtility.ToJsonGameData 对象转为 JSON 格式的字符串。
    4. 加密数据(可选) :如果 encrypDatatrue,调用 EncryptDecrypt 方法加密数据。
    5. 写入文件 :通过 FileStreamStreamWriter 写入数据到文件。
    6. 异常处理:捕获并报告文件操作可能抛出的异常。

Load 方法

  • 功能:从文件中读取数据并反序列化为 GameData 对象。
  • 核心逻辑
    1. 创建完整路径 :和 Save 方法类似,通过 Path.Combine 拼接路径。
    2. 检查文件是否存在 :通过 File.Exists 判断文件是否存在。
    3. 读取数据 :使用 FileStreamStreamReader 读取文件内容。
    4. 解密数据(可选) :如果 encrypDatatrue,调用 EncryptDecrypt 解密数据。
    5. 反序列化 :使用 JsonUtility.FromJson 将 JSON 字符串解析为 GameData 对象。
    6. 异常处理:捕获读取过程中的异常并报告。
cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;

//2024.11.27
public class FileDataHandler
{
    private string dataDirPath = "";//数据文件夹路径
    private string dataFileName = "";//数据文件名

    private bool encrypData=false;//是否加密数据
    private string codeWord = "FuNignNa";//加密密码



    public FileDataHandler(string _dataDirPath, string _dataFileName, bool encrypData)
    {
        dataDirPath = _dataDirPath;
        dataFileName = _dataFileName;
        this.encrypData = encrypData;
        
    }

    public void Save(GameData _data)
    {
        string fullPath = Path.Combine(dataDirPath, dataFileName);


        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));//确保路径中的文件夹被创建

            string dataToStore = JsonUtility.ToJson(_data, true);//将数据转换为json格式

            if (encrypData)
                dataToStore = EncryptDecrypt(dataToStore);//加密数据

            using (FileStream stream = new FileStream(fullPath, FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write(dataToStore);
                }
            }

        }

        catch (Exception e)
        {
            Debug.LogError("保存数据错误: " + fullPath + "\n" + e);
        }
    }

    public GameData Load()
    {
        string fullPath = Path.Combine(dataDirPath, dataFileName);//找到文件路径
        GameData loadData = null;

        if (File.Exists(fullPath))
        {
            try
            {
                string dataToLoad = "";

                using (FileStream stream = new FileStream(fullPath, FileMode.Open))//打开文件
                {
                    using (StreamReader reader = new StreamReader(stream))//读取文件
                    {
                        dataToLoad = reader.ReadToEnd();//读取文件
                    }
                }

                if (encrypData)
                    dataToLoad = EncryptDecrypt(dataToLoad);//解密数据

                loadData = JsonUtility.FromJson<GameData>(dataToLoad);

            }

            catch (Exception e)
            {
                Debug.LogError("读取数据错误: " + fullPath + "\n" + e);
            }
        }


        return loadData;
    }


    public void Delete()//删除数据
    {
        string fullPath = Path.Combine(dataDirPath, dataFileName);//找到文件路径

        if (File.Exists(fullPath))//如果文件存在就删除s
            File.Delete(fullPath);

    }

    private string EncryptDecrypt(string _data)//加密解密
    {
        string modifiedData = "";//修改后的数据

        for (int i = 0; i < _data.Length; i++)
        {
            modifiedData += (char)(_data[i] ^ codeWord[i % codeWord.Length]);  
        }

        return modifiedData;
    }
}
相关推荐
小雪崩1 分钟前
嵌入式学习 day39:TCP并发服务器模型
linux·服务器·c语言·网络·学习·tcp/ip
知识分享小能手15 分钟前
深度学习学习教程,从入门到精通,概率与信息论 — 知识点详解(3)
人工智能·深度学习·学习·数据挖掘·概率论
Wendy不吃榴莲20 分钟前
# AI短剧教程 - 《后西游记》开播后,AI影视为什么更考验“连续讲故事”?
人工智能·笔记·学习·ai·视频
Agudamu116125 分钟前
B站学习视频怎么变笔记:用 Ai好记 + Obsidian 搭建个人知识库的完整教程
人工智能·笔记·学习·音视频
kkkkkkkkkk_Z1 小时前
学嵌入式和Linux应用编程|学习日记:计算机网络基础
linux·学习·计算机网络
麦田里的粮仓1 小时前
图形设计工具箱(免费开源)
学习
每天题库1 小时前
交安C证报考条件有哪些?公路水运安全员C证报名时间及考试科目
学习·安全·考试·题库·考证
lifallen2 小时前
长任务怎样选择遗忘:clearing、compaction 与 memory
人工智能·学习·ai·ai编程
高亦真2 小时前
今天是学习嵌入式的第35天
linux·学习·算法
️学习的小王2 小时前
FastAPI核心知识点与高频易错点总结
学习·fastapi