-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave-load-json.cs
More file actions
80 lines (69 loc) · 2.19 KB
/
Copy pathsave-load-json.cs
File metadata and controls
80 lines (69 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Save/Load System using JSON
// Persist game data to disk using JsonUtility.
// For complex data (dictionaries, polymorphism), use Newtonsoft.Json instead.
using System.IO;
using UnityEngine;
namespace MyGame
{
[System.Serializable]
public class SaveData
{
public string PlayerName;
public int Level;
public float PlayTime;
public Vector3 PlayerPosition;
public int[] InventoryItemIds;
}
public static class SaveSystem
{
private static string SavePath => Path.Combine(Application.persistentDataPath, "save.json");
public static void Save(SaveData data)
{
string json = JsonUtility.ToJson(data, prettyPrint: true);
File.WriteAllText(SavePath, json);
Debug.Log($"Game saved to {SavePath}");
}
public static SaveData Load()
{
if (!File.Exists(SavePath))
{
Debug.Log("No save file found, creating new save data");
return new SaveData();
}
string json = File.ReadAllText(SavePath);
return JsonUtility.FromJson<SaveData>(json);
}
public static bool SaveExists() => File.Exists(SavePath);
public static void DeleteSave()
{
if (File.Exists(SavePath))
{
File.Delete(SavePath);
Debug.Log("Save file deleted");
}
}
}
// Usage example
public class GameSaveManager : MonoBehaviour
{
public void SaveGame()
{
var player = FindFirstObjectByType<PlayerController>();
var data = new SaveData
{
PlayerName = "Player1",
Level = 5,
PlayTime = Time.time,
PlayerPosition = player ? player.transform.position : Vector3.zero,
InventoryItemIds = new[] { 1, 3, 7, 12 }
};
SaveSystem.Save(data);
}
public void LoadGame()
{
if (!SaveSystem.SaveExists()) return;
SaveData data = SaveSystem.Load();
Debug.Log($"Loaded: {data.PlayerName}, Level {data.Level}");
}
}
}