90 lines
2.1 KiB
C#
90 lines
2.1 KiB
C#
|
|
using System;
|
||
|
|
using System.Collections;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using System.IO;
|
||
|
|
using Unity.VisualScripting;
|
||
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
public class SaveManager : MonoBehaviour
|
||
|
|
{
|
||
|
|
private static SaveManager _instance;
|
||
|
|
private string _savePath;
|
||
|
|
|
||
|
|
public SaveData currentSaveData;
|
||
|
|
|
||
|
|
// 存档
|
||
|
|
void Start()
|
||
|
|
{
|
||
|
|
}
|
||
|
|
|
||
|
|
void Update()
|
||
|
|
{
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Awake()
|
||
|
|
{
|
||
|
|
if (_instance == null)
|
||
|
|
{
|
||
|
|
_instance = this;
|
||
|
|
DontDestroyOnLoad(gameObject);
|
||
|
|
_savePath = Application.persistentDataPath + "/save.json";
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
Destroy(gameObject);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void SaveGame()
|
||
|
|
{
|
||
|
|
string json = JsonUtility.ToJson(currentSaveData, true);
|
||
|
|
File.WriteAllText(_savePath, json);
|
||
|
|
Debug.Log("SaveGame Success");
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnButtonDownSaveGameData()
|
||
|
|
{
|
||
|
|
print("SaveGame Start");
|
||
|
|
test();
|
||
|
|
SaveGame();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnButtonDownDeleteGameData()
|
||
|
|
{
|
||
|
|
if (!File.Exists(_savePath)) return;
|
||
|
|
File.Delete(_savePath);
|
||
|
|
Debug.Log("Delete Save Data");
|
||
|
|
}
|
||
|
|
|
||
|
|
private void test()
|
||
|
|
{
|
||
|
|
SaveData _testData = new SaveData();
|
||
|
|
_testData.playerLevel = 10;
|
||
|
|
_testData.gold = 100;
|
||
|
|
_instance.currentSaveData = _testData;
|
||
|
|
SaveGame();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnButtonDownLoadGameData()
|
||
|
|
{
|
||
|
|
if (File.Exists(_savePath))
|
||
|
|
{
|
||
|
|
string json = File.ReadAllText(_savePath);
|
||
|
|
currentSaveData = JsonUtility.FromJson<SaveData>(json);
|
||
|
|
print(currentSaveData.playerLevel);
|
||
|
|
print(currentSaveData.gold);
|
||
|
|
print(currentSaveData);
|
||
|
|
Debug.Log("Load Game Success");
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
Debug.Log("404!!!");
|
||
|
|
currentSaveData = new SaveData
|
||
|
|
{
|
||
|
|
playerLevel = 1,
|
||
|
|
gold = 0
|
||
|
|
}; // 没有存档就创建一个默认存档
|
||
|
|
SaveGame();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|