103 lines
2.5 KiB
C#
103 lines
2.5 KiB
C#
using System.IO;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
|
|
public class InventoryData
|
|
{
|
|
// energy
|
|
public int energy;
|
|
|
|
//Health
|
|
public int health;
|
|
|
|
//Gems
|
|
public int gems;
|
|
|
|
public InventoryData(int energy, int health, int gems)
|
|
{
|
|
this.energy = energy;
|
|
this.health = health;
|
|
this.gems = gems;
|
|
}
|
|
}
|
|
|
|
public class InventoryScript : MonoBehaviour
|
|
{
|
|
string filename = "inventoryData.txt";
|
|
string path;
|
|
InventoryData inventoryData;
|
|
|
|
[Header("Variables")]
|
|
//Energy
|
|
[SerializeField] int energy;
|
|
|
|
//Health
|
|
[SerializeField] int health;
|
|
|
|
//Gems
|
|
[SerializeField] int gems;
|
|
|
|
|
|
|
|
private void Awake()
|
|
{
|
|
path = Path.Combine(Application.persistentDataPath, filename);
|
|
if (!File.Exists(path))
|
|
{
|
|
Debug.Log("erzeuge leeres File");
|
|
File.WriteAllText(path, "");
|
|
}
|
|
}
|
|
private void Start()
|
|
{
|
|
ReadInventoryData();
|
|
}
|
|
|
|
public int Energy
|
|
{
|
|
get { return energy; }
|
|
set { energy = value; ValChanged(); }
|
|
}
|
|
|
|
public int Health
|
|
{
|
|
get { return health; }
|
|
set { health = value; ValChanged(); }
|
|
}
|
|
public int Gems
|
|
{
|
|
get { return gems; }
|
|
set { gems = value; ValChanged(); }
|
|
}
|
|
|
|
// Achtung, ValChanged wird NICHT aufgerufen, wenn man die Werte im Inspector verändert,
|
|
// weil das nur die Felder, nicht die Properties setzt.
|
|
// Ändert man aber per Script die Property, wird ValChanged aufgerufen und sofort die Werte ins File gespeichert.
|
|
// Solche Werte sollte man dann auch nicht in jedem Frame ändern, sondern nur, wenn der Spieler klickt.
|
|
private void ValChanged()
|
|
{
|
|
Debug.Log("ValChanged");
|
|
SaveInventoryData();
|
|
}
|
|
private void ReadInventoryData()
|
|
{
|
|
string datastring = File.ReadAllText(path);
|
|
if (datastring == "")
|
|
{
|
|
Debug.Log("File ist noch leer, bitte erst etwas schreiben");
|
|
return;
|
|
}
|
|
inventoryData = JsonUtility.FromJson<InventoryData>(datastring);
|
|
energy = inventoryData.energy;
|
|
health = inventoryData.health;
|
|
gems = inventoryData.gems;
|
|
}
|
|
private void SaveInventoryData()
|
|
{
|
|
inventoryData = new InventoryData(energy, health, gems); // erstellt ein neues Objekt InventoryData aus den Werten dieses Scripts
|
|
string datastring = JsonUtility.ToJson(inventoryData); // macht einen JSON String aus diesem Objekt (dafür brauchen wir es auch nur)
|
|
File.WriteAllText(path, datastring);
|
|
}
|
|
|
|
}
|