using System; using System.IO; using Data.ScriptableObjects; using Types; using UnityEngine; using UnityEngine.Serialization; using Random = UnityEngine.Random; namespace Managers { [Serializable] public class SaveManager : MonoBehaviour { public static SaveManager Instance; public ItemDatabase itemDatabase; [FormerlySerializedAs("DefaultPlayerData")] public GamePlayerSo defaultPlayerData; public GameState GameState; private void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); GameState = new GameState(); } else { Destroy(gameObject); } } public void SaveGame(PlayerManager playerManager) { GameState.Players[0].CurrentMap = MapManager.Instance.currentMapSo.name; // gameState.playerData.currentPosition = playerManager.transform.position; var json = JsonUtility.ToJson(GameState); File.WriteAllText(Application.persistentDataPath + "/gameState.json", json); } public void LoadGame(GameState gs) { GameState = gs; // playerManager.Initialize(gameState.playerData); // todo: enable map // MapManager.Instance.GetMap(gameState.playerData.currentMap); /*var path = Application.persistentDataPath + "/gameState.json"; if (File.Exists(path)) { var json = File.ReadAllText(path); gameState = JsonUtility.FromJson(json); }*/ } public void LoadGame() { var path = Application.persistentDataPath + "/gameState.json"; if (File.Exists(path)) { var json = File.ReadAllText(path); GameState = JsonUtility.FromJson(json); } } public void NewGame() { // create new instance of player data var newPlayerData = new GamePlayer(defaultPlayerData); GameState.Players.Add(0, newPlayerData); // add items to inventory if (itemDatabase == null) itemDatabase = Resources.Load("GameItems"); if (itemDatabase == null) { Debug.LogError("ItemDatabase is null"); //TODO: remove? LoadGame(GameState); return; } if (itemDatabase.AllItems.Count == 0) itemDatabase.LoadAllItems(); Debug.Log("Item count: " + itemDatabase.AllItems.Count); for (var i = 0; i < 10; i++) { // set slot to random item var item = itemDatabase.AllItems[ Random.Range(0, itemDatabase.AllItems.Count - 1)]; GameState.Players[0].AddItemToInventory(item); } LoadGame(GameState); } } }