Skip to content
Snippets Groups Projects
Commit 2530a84e authored by Margaretha Olivia's avatar Margaretha Olivia
Browse files

fix: save system

parent bc96aaed
No related merge requests found
Showing with 269 additions and 0 deletions
fileFormatVersion: 2
guid: e7fc8ed2bdad40e419949dcbef76dba9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 0a7799ad29900e243b18f05ebf641e14
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class GameData
{
public int currentLevel;
public Vector3 playerPosition;
// from PlayerHealth.cs
public int currentHealth;
public bool godMode;
// from PlayerMovement.cs
public float speed;
public bool isDoubleSpeed;
// from PlayerShooting.cs
public int damagePerShot;
public bool isOneHitKill;
// from PlayerGold.cs
public int currentGold;
public bool isMotherlode;
public List<PetData> pet = new List<PetData>();
// the values defined in this constructor will be the default values
// the game starts with when there's no data to load
public GameData()
{
}
}
[System.Serializable]
public class PetData
{
public string type;
public int currentHealth;
public int damagePerShot;
public float speed;
}
\ No newline at end of file
fileFormatVersion: 2
guid: 3c28cba78b9fedf4d9b02eda17c76378
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class DataPersistenceManager : MonoBehaviour
{
[Header("File Storage Config")]
[SerializeField] private string fileName;
private GameData gameData;
private List<IDataPersistence> dataPersistenceObjects;
private FileDataHandler dataHandler;
public static DataPersistenceManager instance { get; private set; }
private void Awake()
{
if (instance != null)
{
Debug.LogError("Found more than one Data Persistence Manager in the scene.")
};
instance = this;
}
private void Start()
{
this.dataHandler = new FileDataHandler(Application.persistentDataPath, fileName);
this.dataPersistenceObjects = FindAllDataPersistenceObjects();
LoadGame();
}
public void NewGame()
{
this.gameData = new GameData();
}
public void LoadGame()
{
// load any saved data from a file using data handler
this.gameData = dataHandler.Load();
// if no data can be loaded, initialize to a new game
if (this.gameData == null)
{
Debug.Log("Mo data was found. Initializing data to defaults");
NewGame();
}
// push the loaded data to all other scripts that need it
foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
{
dataPersistenceObj.LoadData(gameData);
}
Debug.Log("Loaded game data");
}
public void SaveGame()
{
// pass the data to other scripts so they can update it
foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
{
dataPersistenceObj.SaveData(ref gameData);
}
Debug.Log("Saved game data");
// save that data to a file using data handler
dataHandler.Save(gameData);
}
private void OnApplicationQuit()
{
SaveGame();
}
private List<IDataPersistence> FindAllDataPersistenceObjects()
{
IEnumerable<IDataPersistence> dataPersistenceObjects = FindObjectsOfType<MonoBehaviour>().OfType<IDataPersistence>();
return new List<IDataPersistence>(dataPersistenceObjects);
}
}
fileFormatVersion: 2
guid: 3dcebec8b76c1cb44ac0cb6a99c71ac6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
public class FileDataHandler
{
private string dataDirPath = "";
private string dataFileName = "";
public FileDataHandler(string dataDirPath, string dataFileName)
{
this.dataDirPath = dataDirPath;
this.dataFileName = dataFileName;
}
public GameData Load()
{
// use Path.combine to account for different OS's having different path separators
string fullPath = Path.Combine(dataDirPath, dataFileName);
GameData loadedData = null;
if (File.Exists(fullPath))
{
try
{
// load the serialized data from the file
string dataToLoad = "";
using (FileStream stream = new FileStream(fullPath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
dataToLoad = reader.ReadToEnd();
}
}
//deserialize the data from Json back into the C# object
loadedData = JsonUtility.FromJson<GameData>(dataToLoad);
}
catch (Exception e)
{
Debug.LogError("Error occured when trying to load data to file: " + fullPath + "\n" + e);
}
}
}
public void Save(GameData data)
{
// use Path.combine to account for different OS's having different path separators
string fullPath = Path.Combine(dataDirPath, dataFileName);
try
{
// create the directory the file will be written to if it doesn't already exist
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
//serialize the C# game data object into Json
string dataToStore = JsonUtility.ToJson(data, true);
// write the serialized data to the file
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(dataToStore);
}
}
}
catch (Exception e)
{
Debug.LogError("Error occured when trying to save data to file: " + fullPath + "\n" + e);
}
}
}
fileFormatVersion: 2
guid: 09e9d558054597e408a7c247b33606db
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IDataPersistence
{
void LoadData(GameData data);
void SaveData(ref GameData data);
}
fileFormatVersion: 2
guid: 68658cb79c76d4041b7ba6999d30ffa1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
/*
using static UnityEditor.Progress;
using System.Collections.Generic;
using System;
......@@ -60,3 +61,4 @@ public class PetData
public int damagePerShot;
public float speed;
}
*/
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment