feat: read from JSON file, level information

This commit is contained in:
2025-02-09 12:40:23 +01:00
parent ed5d3cd222
commit e35359f89a
2 changed files with 27 additions and 21 deletions

View File

@ -1,38 +1,41 @@
using System.IO;
using System.Runtime.Serialization.Json;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
using System.IO;
using System.Text.Json;
public class LevelLoader : MonoBehaviour public class LevelLoader : MonoBehaviour
{ {
[SerializeField]
public Text levelNameText; public Text levelNameText;
private Level level;
void Start() void Start()
{ {
levelNameText.text = "Coucou"; LoadLevel();
string filePath = "level.json"; if (level != null)
if (File.Exists(filePath))
{ {
string json = File.ReadAllText(filePath); levelNameText.text = level.Name;
Level level = JsonSerializer.Deserialize<Level>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
Console.WriteLine($"Name: {level.Name}");
Console.WriteLine($"MusicPath: {level.MusicPath}");
Console.WriteLine($"TotalJumps: {level.TotalJumps}");
Console.WriteLine($"TotalAttempts: {level.TotalAttempts}");
Console.WriteLine($"KilledCount: {level.KilledCount}");
} }
else else
{ {
Console.WriteLine("JSON file not found."); levelNameText.text = "Failed to Load Level";
} }
} }
void Update() void LoadLevel()
{ {
string path = Path.Combine(Application.dataPath, "Levels", "back-on-track.json");
if (File.Exists(path))
{
string json = File.ReadAllText(path);
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Level));
level = (Level)serializer.ReadObject(stream);
}
}
else
{
Debug.LogError("Level file not found: " + path);
}
} }
} }

View File

@ -1,6 +1,9 @@
{ {
"name": "Back on Track", "Name": "Back on Track",
"music": "", "MusicPath": "back-on-track.mp3",
"TotalJumps": 0,
"TotalAttempts": 0,
"KilledCount": 0,
"elements": [ "elements": [
{ {
"type": "Spike", "type": "Spike",