类银河恶魔城 P15-1 Save System

发布于:2025-07-03 ⋅ 阅读:(19) ⋅ 点赞:(0)

FiledataHandler.cs 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using Unity.VisualScripting;


public class FiledataHandler 
{
    private string dataDirPath = "";
    private string dataFileName = "";

    public FiledataHandler(string _dataDirPath, string _dataFileName  )
    {
        dataDirPath = _dataDirPath;
        dataFileName = _dataFileName;
    }

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

        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

            string dataToStore = JsonUtility.ToJson( _data,true);
            using (FileStream stream = new FileStream(fullPath, FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write(dataToStore);
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Error on trying to save data to file: " + 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(StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.Write(dataToLoad);
                    }
                }
                loadData = JsonUtility.FromJson<GameData>(dataToLoad);
            }
            catch (Exception e)
            {
                Debug.LogError("Error on trying to save data to file: " + fullPath + "\n" + e);

            }
        }
        return loadData;
    }

    }

 SaveManager.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class SaveManager : MonoBehaviour
{
    public static SaveManager instance;

    [SerializeField] private string fileName;

    private GameData gameData;

    private List<ISaveManager> saveManagers;
    private FiledataHandler dataHandler;


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

    private void Start()
    {
        dataHandler = new FiledataHandler(Application.persistentDataPath,fileName);

        saveManagers = FindAllSaveManagers();

        LoadGame();
    }

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

    public void LoadGame()
    {
        gameData = dataHandler.Load();
        // game data = data
        if (this.gameData == null)
        {

            NewGame();
        }

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

    public void SaveGame()
    {
        // data handler save gameData
        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>().OfType<ISaveManager>();

        return new List<ISaveManager>(saveManagers);

    }

}

 GameData.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class GameData 
{
    public int currencey;

    public GameData()
    {
        this.currencey = 0;
    }
}

ISaveManager.cs 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface ISaveManager 
{
    void LoadData(GameData _data);

    void SaveData(ref GameData _data);
}

 PlayerManager.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerManager : MonoBehaviour,ISaveManager
{
    public static PlayerManager instance;
    public Player player;

    public int currency;

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


    public bool HaveEnoughMoney(int _Price)
    {
        if(_Price > currency)
        {
            Debug.Log("Not enough money");
            return false;
        }

        currency = currency - _Price;
        return true;
    }

    public int GetCurrentCurrency() => currency;

    public void LoadData(GameData _data)
    {
        this.currency = _data.currencey;
    }

    public void SaveData(ref GameData _data)
    {
        _data.currencey = this.currency;
    }
}
  1. 在Unity中,Application.persistentDataPath 是用于存储持久化数据的路径,其值会根据操作系统和项目设置自动生成。您提供的路径 C:/Users/xxxx/AppData/LocalLow/CompanyName/ProductName 是典型的Windows平台路径,解析如下:


    路径结构解析

    路径部分 说明
    C:/Users/xxxx/ 当前用户的个人文件夹(xxxx 是您的Windows用户名)
    AppData/LocalLow/ 系统隐藏目录,存储权限较低的应用数据(需在文件资源管理器开启“显示隐藏文件”)
    CompanyName/ 在Unity的 Player Settings ➔ Company Name 中设置的名称
    ProductName/ 在Unity的 Player Settings ➔ Product Name 中设置的应用名称

    关键特性

    • 跨平台一致性
      Unity会自动适配不同操作系统的路径:

      • WindowsC:/Users/xxxx/AppData/LocalLow/CompanyName/ProductName

      • macOS/Users/xxxx/Library/Application Support/CompanyName/ProductName

      • Android/storage/emulated/0/Android/data/<package.name>/files

      • iOS/var/mobile/Containers/Data/Application/<GUID>/Documents

我的是以下

C:\Users\Administrator\AppData\LocalLow\DefaultCompany\RPG-Udemy Course