WXMC/.svn/pristine/6d/6dd4a8559b7eb3f5c344959ff7c1dc8c2303caee.svn-base
2024-12-04 16:18:46 +08:00

174 lines
3.5 KiB
Plaintext

using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
[System.Serializable]
public struct PHomeGameSave
{
public int Gem;
public List<PHomeInventoryItem> Items;
}
public class PHomeInventory : MonoBehaviour
{
public static PHomeInventory instance = null;
[SerializeField]
private int m_gemCount;
public PuzzleGameMode.VoidDelegate OnAfterGemCountChanged;
public int GemCount
{
get
{
return m_gemCount;
}
set
{
if (m_gemCount != value)
{
m_gemCount = value;
OnAfterGemCountChanged?.Invoke();
}
}
}
[SerializeField]
protected List<PHomeInventoryItem> m_items;
public List<PHomeInventoryItem> Items
{
get
{
return m_items;
}
set
{
if (m_items != value)
{
m_items = value;
}
}
}
[SerializeField]
protected PHomeWorldBall m_useWorldBall;
public PHomeWorldBall UseWorldBall
{
get
{
return m_useWorldBall;
}
set
{
if (m_useWorldBall != value)
{
m_useWorldBall = value;
}
}
}
[BoxGroup("Debug")]
[HideInPlayMode]
[SerializeField]
private List<PHomeWorldBall> m_startWorldBalls;
private void OnDestroy()
{
Save();
}
#region Save
[SerializeField]
private string m_saveName = "game.sav";
private string GetSavePath()
{
return Path.Combine(Application.persistentDataPath, m_saveName);
}
[Button]
public void Save()
{
PHomeGameSave save = new PHomeGameSave()
{
Gem = m_gemCount,
Items = m_items.ToList(),
};
string savePath = GetSavePath();
string saveStr = UnitySerializer.Instance.Serialize(save);
byte[] saveBytes = Encoding.UTF8.GetBytes(saveStr);
if (File.Exists(savePath))
{
File.Delete(savePath);
}
File.WriteAllBytes(savePath, saveBytes);
print($"Game saved, {saveBytes.Length} written to {savePath}");
}
[Button]
public void Load()
{
string savePath = GetSavePath();
if (!File.Exists(savePath))
{
throw new System.Exception($"Save file not exist {savePath}");
}
byte[] saveBytes = File.ReadAllBytes(savePath);
string saveStr = Encoding.UTF8.GetString(saveBytes);
PHomeGameSave save = UnitySerializer.Instance.Deserialize<PHomeGameSave>(saveStr);
GemCount = save.Gem;
Items = save.Items.ToList();
print($"Game loaded, {saveBytes.Length} read from {savePath}");
}
[Button]
public void ClearSave()
{
string savePath = GetSavePath();
if (HasSave())
{
File.Delete(savePath);
print($"Save file deleted: {savePath}");
}
else
{
print($"Nothing to delete at {savePath}");
}
}
public bool HasSave()
{
return File.Exists(GetSavePath());
}
#endregion
void Awake()
{
instance = this;
if (HasSave())
{
Load();
}
else
{
foreach (var item in m_startWorldBalls)
{
m_items.Add(item);
}
}
}
}