Refactoring your level management system to centralize the logic within the GameStructureManager is an excellent approach. This not only streamlines your codebase but also makes it easier to manage and maintain level states across your game. Below, I'll provide a comprehensive guide on how to integrate your existing Level script with the new GameStructureManager, ensuring a centralized and efficient level management system.
Overview of the Refactored System
- Centralized Data Management: Move all level-related data management to the
GameStructureManager. This includes tracking whether levels are unlocked or completed.
- Simplified Level Scripts: Update the
Level scripts to interact with the GameStructureManager for their state instead of maintaining their own state.
- Unified Saving and Loading: Handle all saving and loading of game data within the
GameStructureManager, ensuring consistency across all levels.
Step-by-Step Integration
1. Modify the GameStructureManager
Firstly, we need to ensure that the GameStructureManager handles all aspects of level data, including saving and loading. We'll implement the IDataPersistence interface directly in the GameStructureManager.
a. Implement IDataPersistence Interface
Assuming you have an IDataPersistence interface that requires LoadData and SaveData methods, we'll implement these in the GameStructureManager.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[System.Serializable]
public class GameData
{
public Dictionary<string, List<FloorData>> gameStructure = new Dictionary<string, List<FloorData>>();
public Dictionary<string, int> realmCompletionAmount = new Dictionary<string, int>();
public string currentRealm;
public int currentFloor;
public int currentLevel;
}
public class GameStructureManager : MonoBehaviour, IDataPersistence
{
public static GameStructureManager Instance;
[SerializeField] private int realmCount = 6;
[SerializeField] private int floorsPerRealm = 10;
[SerializeField] private int levelsPerFloor = 3;
[SerializeField] private int totalEliteBattles = 30;
private Dictionary<string, List<FloorData>> gameStructure = new Dictionary<string, List<FloorData>>();
private Dictionary<string, int> realmCompletionAmount = new Dictionary<string, int>();
private (string realm, int floor, int level) currentLevel;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
// Game structure will be generated in LoadData if no saved data exists
}
else
{
Destroy(gameObject);
}
}
public void LoadData(GameData data)
{
if (data.gameStructure != null && data.gameStructure.Count > 0)
{
gameStructure = data.gameStructure;
realmCompletionAmount = data.realmCompletionAmount;
}
else
{
GenerateGameStructure();
}
currentLevel = (data.currentRealm, data.currentFloor, data.currentLevel);
}
public void SaveData(GameData data)
{
data.gameStructure = gameStructure;
data.realmCompletionAmount = realmCompletionAmount;
data.currentRealm = currentLevel.realm;
data.currentFloor = currentLevel.floor;
data.currentLevel = currentLevel.level;
}
private void GenerateGameStructure()
{
string[] realmNames = { "Fire", "Water", "Earth", "Air", "Light", "Dark" };
for (int r = 0; r < realmCount; r++)
{
List<FloorData> realm = new List<FloorData>();
int eliteBattlesInRealm = totalEliteBattles / realmCount;
for (int f = 0; f < floorsPerRealm; f++)
{
FloorData floor = new FloorData();
// Set floor type
if (f == 0)
floor.Type = FloorType.NormalBattle;
else if (f == floorsPerRealm - 1)
floor.Type = FloorType.BossBattle;
else if (f == 2)
floor.Type = FloorType.Event;
else
floor.Type = (FloorType)UnityEngine.Random.Range(0, 3); // Exclude BossBattle
// Generate levels for the floor
for (int l = 0; l < (floor.Type == FloorType.BossBattle ? 1 : levelsPerFloor); l++)
{
LevelData level = new LevelData
{
Type = floor.Type,
LevelStep = f,
FloorIndex = f,
LevelIndex = l,
IsUnlocked = (f == 0 && l == 0), // Only the first level of the first floor is initially unlocked
IsCompleted = false
};
if (level.Type == FloorType.Event)
{
level.EventType = (EventType)UnityEngine.Random.Range(0, 4);
}
else if (level.Type == FloorType.NormalBattle || level.Type == FloorType.EliteBattle)
{
level.EnemyCount = UnityEngine.Random.Range(1, 6);
}
floor.Levels.Add(level);
}
// Distribute elite battles
if (floor.Type != FloorType.BossBattle && floor.Type != FloorType.Event && eliteBattlesInRealm > 0)
{
int eliteCount = Mathf.Min(eliteBattlesInRealm, levelsPerFloor - 1);
for (int e = 0; e < eliteCount; e++)
{
int randomIndex = UnityEngine.Random.Range(0, floor.Levels.Count);
if (floor.Levels[randomIndex].Type == FloorType.NormalBattle) // Prevent overriding already elite
{
floor.Levels[randomIndex].Type = FloorType.EliteBattle;
eliteBattlesInRealm--;
}
}
}
realm.Add(floor);
}
string realmName = realmNames[r];
gameStructure.Add(realmName, realm);
realmCompletionAmount.Add(realmName, 0);
}
}
public LevelData GetLevelData(string realmName, int floorIndex, int levelIndex)
{
if (gameStructure.TryGetValue(realmName, out List<FloorData> realm))
{
if (floorIndex >= 0 && floorIndex < realm.Count)
{
FloorData floor = realm[floorIndex];
if (levelIndex >= 0 && levelIndex < floor.Levels.Count)
{
return floor.Levels[levelIndex];
}
}
}
return null;
}
public void UpdateLevelStatus(string realmName, int floorIndex, int levelIndex, bool isUnlocked, bool isCompleted)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
if (level != null)
{
level.IsUnlocked = isUnlocked;
level.IsCompleted = isCompleted;
}
}
public void SetEnteredLevel(string realmName, int floorIndex, int levelIndex)
{
currentLevel = (realmName, floorIndex, levelIndex);
}
public List<LevelData> GetNextLevels(string realmName, int floorIndex, int levelIndex)
{
List<LevelData> nextLevels = new List<LevelData>();
if (gameStructure.TryGetValue(realmName, out var realm))
{
// Check for next level in the same floor
if (levelIndex + 1 < realm[floorIndex].Levels.Count)
{
LevelData nextLevel = realm[floorIndex].Levels[levelIndex + 1];
nextLevels.Add(nextLevel);
}
// If last level in the floor, add levels from the next floor
else if (floorIndex + 1 < realm.Count)
{
var nextFloor = realm[floorIndex + 1];
nextLevels.AddRange(nextFloor.Levels);
}
}
return nextLevels;
}
public void UnlockLevel(string realmName, int floorIndex, int levelIndex)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
if (level != null)
{
level.IsUnlocked = true;
}
}
public bool IsRealmCompleted(string realmName)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
return realm.All(floor => floor.Levels.All(level => level.IsCompleted));
}
return false;
}
public void ResetRealm(string realmName)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
foreach (var floor in realm)
{
foreach (var level in floor.Levels)
{
level.IsUnlocked = false;
level.IsCompleted = false;
}
}
// Unlock the first level of the first floor
if (realm.Count > 0 && realm[0].Levels.Count > 0)
{
realm[0].Levels[0].IsUnlocked = true;
}
// Increment realm completion amount
realmCompletionAmount[realmName]++;
}
}
public void LockLevelsInStep(string realmName, int levelStep)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
foreach (var floor in realm)
{
foreach (var level in floor.Levels)
{
if (level.LevelStep == levelStep && !level.IsCompleted)
{
level.IsUnlocked = false;
}
}
}
}
}
public int GetRealmCompletionAmount(string realmName)
{
if (realmCompletionAmount.TryGetValue(realmName, out int amount))
{
return amount;
}
return 0;
}
public bool IsPreviousLevelCompleted(string realmName, int floorIndex, int levelIndex)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
if (floorIndex > 0)
{
var previousFloor = realm[floorIndex - 1];
return previousFloor.Levels.All(level => level.IsCompleted);
}
else if (levelIndex > 0)
{
return realm[floorIndex].Levels[levelIndex - 1].IsCompleted;
}
}
return true; // First level of the first floor is always considered "unlocked"
}
public FloorType GetFloorType(string realmName, int floorIndex)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
if (floorIndex >= 0 && floorIndex < realm.Count)
{
return realm[floorIndex].Type;
}
}
return FloorType.NormalBattle; // Default to normal battle if not found
}
// Method to get all levels in a realm
public List<LevelData> GetAllLevelsInRealm(string realmName)
{
List<LevelData> allLevels = new List<LevelData>();
if (gameStructure.TryGetValue(realmName, out var realm))
{
foreach (var floor in realm)
{
allLevels.AddRange(floor.Levels);
}
}
return allLevels;
}
// Method to get the current level data
public LevelData GetCurrentLevelData()
{
return GetLevelData(currentLevel.realm, currentLevel.floor, currentLevel.level);
}
// Method to check if a level is unlocked
public bool IsLevelUnlocked(string realmName, int floorIndex, int levelIndex)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
return level != null && level.IsUnlocked;
}
// Method to get the number of completed levels in a realm
public int GetCompletedLevelCount(string realmName)
{
int count = 0;
if (gameStructure.TryGetValue(realmName, out var realm))
{
count = realm.Sum(floor => floor.Levels.Count(level => level.IsCompleted));
}
return count;
}
// Method to get the total number of levels in a realm
public int GetTotalLevelCount(string realmName)
{
int count = 0;
if (gameStructure.TryGetValue(realmName, out var realm))
{
count = realm.Sum(floor => floor.Levels.Count);
}
return count;
}
// New method to complete a level
public void CompleteLevel(string realmName, int floorIndex, int levelIndex)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
if (level != null && level.IsUnlocked && !level.IsCompleted)
{
level.IsCompleted = true;
// Unlock the next level
if (levelIndex + 1 < gameStructure[realmName][floorIndex].Levels.Count)
{
UnlockLevel(realmName, floorIndex, levelIndex + 1);
}
else if (floorIndex + 1 < gameStructure[realmName].Count)
{
var nextFloor = gameStructure[realmName][floorIndex + 1];
foreach (var nextLevel in nextFloor.Levels)
{
UnlockLevel(realmName, floorIndex + 1, nextLevel.LevelIndex);
}
}
// Check for realm completion
if (IsRealmCompleted(realmName))
{
Debug.Log($"Realm {realmName} completed!");
// Perform additional actions if needed
}
// Optionally, save the game immediately after completion
// DataPersistenceManager.instance.Save();
}
}
}
Key Changes:
- Data Persistence: The
GameStructureManager now implements IDataPersistence, handling both saving and loading of the game data.
- Level Completion: A new method
CompleteLevel handles the completion of a level, unlocking subsequent levels and checking for realm completion.
- GameData Structure: Updated
GameData to include separate fields for the current level's realm, floor, and level indices for better serialization compatibility.
2. Refactor the Level Script
Next, we'll refactor the Level script to interact with the GameStructureManager instead of maintaining its own state.
using System;
using UnityEngine;
using UnityEngine.UI;
public class Level : MonoBehaviour
{
[Header("Level Identification")]
[SerializeField] private string realmName;
[SerializeField] private int floorIndex;
[SerializeField] private int levelIndex;
private Button levelButton;
private Image levelImage;
private void Awake()
{
// Ensure the button and image components are attached
levelButton = GetComponent<Button>();
levelImage = GetComponent<Image>();
if (levelButton == null || levelImage == null)
{
Debug.LogError("Level script requires Button and Image components.");
}
// Set transparency for clickable UI elements
levelImage.alphaHitTestMinimumThreshold = 0.01f;
}
private void Start()
{
UpdateLevelButton();
}
// Updates the visual and interactable state of the level button
private void UpdateLevelButton()
{
LevelData levelData = GameStructureManager.Instance.GetLevelData(realmName, floorIndex, levelIndex);
if (levelData != null)
{
if (levelData.IsUnlocked)
{
if (levelData.IsCompleted)
{
levelButton.interactable = false;
levelImage.color = new Color(0f, 0f, 1f, 0.5f); // Blue with transparency
}
else
{
levelButton.interactable = true;
levelImage.color = new Color(1f, 1f, 1f); // White
}
}
else
{
levelButton.interactable = false;
levelImage.color = new Color(0.5f, 0.5f, 0.5f, 0f); // Grey and transparent
}
}
else
{
// If level data is not found, lock the level
levelButton.interactable = false;
levelImage.color = new Color(0.5f, 0.5f, 0.5f, 0f);
}
}
// Method called when the level button is clicked to load the level
public void LoadLevel(string levelToLoad)
{
Debug.Log($"Loading level: {levelToLoad}");
GameStructureManager.Instance.SetEnteredLevel(realmName, floorIndex, levelIndex);
DataPersistenceManager.instance.LoadSceneAsync(levelToLoad);
}
// Method to mark the level as completed
public void CompleteLevel()
{
GameStructureManager.Instance.CompleteLevel(realmName, floorIndex, levelIndex);
UpdateLevelButton();
}
// Optional: Refresh the level button UI (can be called externally if needed)
public void Refresh()
{
UpdateLevelButton();
}
}
Key Changes:
- Identification Fields: Added
realmName, floorIndex, and levelIndex as serialized fields to uniquely identify each level. Assign these in the Unity Inspector for each level object.
- State Management: Removed internal
isUnlocked and isCompleted fields. The script now queries the GameStructureManager for the current state.
- UI Updates: The
UpdateLevelButton method updates the button's appearance and interactability based on the level's state from the GameStructureManager.
- Level Completion: The
CompleteLevel method notifies the GameStructureManager to update the level's state and refreshes the UI accordingly.
3. Update Your Unity Scene
Ensure that each level object in your Unity scene has the updated Level script attached. Assign the realmName, floorIndex, and levelIndex appropriately in the Inspector to correspond with your game structure.
4. Handling Data Persistence
Since the GameStructureManager now handles all data persistence, ensure that your DataPersistenceManager correctly invokes the LoadData and SaveData methods of the GameStructureManager.
Here's a basic example of how your DataPersistenceManager might interact with the GameStructureManager:
using UnityEngine;
public class DataPersistenceManager : MonoBehaviour
{
public static DataPersistenceManager instance;
public GameData gameData;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
// Load game data here
LoadGame();
}
else
{
Destroy(gameObject);
}
}
public void LoadGame()
{
// Implement your loading logic (e.g., from JSON, PlayerPrefs, etc.)
// After loading, pass the data to the GameStructureManager
GameStructureManager.Instance.LoadData(gameData);
}
public void SaveGame()
{
// Implement your saving logic
// Before saving, get the data from the GameStructureManager
GameStructureManager.Instance.SaveData(gameData);
// Then serialize `gameData` to your storage solution
}
public void LoadSceneAsync(string sceneName)
{
// Implement your asynchronous scene loading here
// Possibly call SaveGame before loading a new scene
SaveGame();
UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName);
}
}
Note: Adjust the LoadGame and SaveGame methods according to your actual data storage mechanism (e.g., JSON, binary files, etc.).
5. Ensure Serializability of Data Classes
Ensure that your data classes (LevelData, FloorData, and GameData) are serializable. Unity's JsonUtility has limitations with serializing dictionaries and nullable types, so you might need to adjust your serialization strategy or use a more robust JSON library like Newtonsoft.Json.
Example using Newtonsoft.Json:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
[Serializable]
public class LevelData
{
public FloorType Type;
public EventType? EventType;
public int EnemyCount;
public int LevelStep;
public bool IsUnlocked;
public bool IsCompleted;
public int FloorIndex;
public int LevelIndex;
}
[Serializable]
public class FloorData
{
public FloorType Type;
public List<LevelData> Levels = new List<LevelData>();
}
[Serializable]
public class GameData
{
public Dictionary<string, List<FloorData>> gameStructure = new Dictionary<string, List<FloorData>>();
public Dictionary<string, int> realmCompletionAmount = new Dictionary<string, int>();
public string currentRealm;
public int currentFloor;
public int currentLevel;
}
Ensure you have the Newtonsoft.Json package installed via the Unity Package Manager or by importing the DLL.
6. Testing the Refactored System
After implementing the above changes, thoroughly test the system to ensure:
- Levels unlock and lock as expected.
- Completion of a level correctly updates the state and unlocks subsequent levels.
- Data persistence accurately saves and loads game states across sessions.
- UI updates reflect the current state of each level appropriately.
Final Code Files
GameStructureManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[System.Serializable]
public class GameData
{
public Dictionary<string, List<FloorData>> gameStructure = new Dictionary<string, List<FloorData>>();
public Dictionary<string, int> realmCompletionAmount = new Dictionary<string, int>();
public string currentRealm;
public int currentFloor;
public int currentLevel;
}
public class GameStructureManager : MonoBehaviour, IDataPersistence
{
public static GameStructureManager Instance;
[SerializeField] private int realmCount = 6;
[SerializeField] private int floorsPerRealm = 10;
[SerializeField] private int levelsPerFloor = 3;
[SerializeField] private int totalEliteBattles = 30;
private Dictionary<string, List<FloorData>> gameStructure = new Dictionary<string, List<FloorData>>();
private Dictionary<string, int> realmCompletionAmount = new Dictionary<string, int>();
private (string realm, int floor, int level) currentLevel;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
// Game structure will be generated in LoadData if no saved data exists
}
else
{
Destroy(gameObject);
}
}
public void LoadData(GameData data)
{
if (data.gameStructure != null && data.gameStructure.Count > 0)
{
gameStructure = data.gameStructure;
realmCompletionAmount = data.realmCompletionAmount;
}
else
{
GenerateGameStructure();
}
currentLevel = (data.currentRealm, data.currentFloor, data.currentLevel);
}
public void SaveData(GameData data)
{
data.gameStructure = gameStructure;
data.realmCompletionAmount = realmCompletionAmount;
data.currentRealm = currentLevel.realm;
data.currentFloor = currentLevel.floor;
data.currentLevel = currentLevel.level;
}
private void GenerateGameStructure()
{
string[] realmNames = { "Fire", "Water", "Earth", "Air", "Light", "Dark" };
for (int r = 0; r < realmCount; r++)
{
List<FloorData> realm = new List<FloorData>();
int eliteBattlesInRealm = totalEliteBattles / realmCount;
for (int f = 0; f < floorsPerRealm; f++)
{
FloorData floor = new FloorData();
// Set floor type
if (f == 0)
floor.Type = FloorType.NormalBattle;
else if (f == floorsPerRealm - 1)
floor.Type = FloorType.BossBattle;
else if (f == 2)
floor.Type = FloorType.Event;
else
floor.Type = (FloorType)UnityEngine.Random.Range(0, 3); // Exclude BossBattle
// Generate levels for the floor
for (int l = 0; l < (floor.Type == FloorType.BossBattle ? 1 : levelsPerFloor); l++)
{
LevelData level = new LevelData
{
Type = floor.Type,
LevelStep = f,
FloorIndex = f,
LevelIndex = l,
IsUnlocked = (f == 0 && l == 0), // Only the first level of the first floor is initially unlocked
IsCompleted = false
};
if (level.Type == FloorType.Event)
{
level.EventType = (EventType)UnityEngine.Random.Range(0, 4);
}
else if (level.Type == FloorType.NormalBattle || level.Type == FloorType.EliteBattle)
{
level.EnemyCount = UnityEngine.Random.Range(1, 6);
}
floor.Levels.Add(level);
}
// Distribute elite battles
if (floor.Type != FloorType.BossBattle && floor.Type != FloorType.Event && eliteBattlesInRealm > 0)
{
int eliteCount = Mathf.Min(eliteBattlesInRealm, levelsPerFloor - 1);
for (int e = 0; e < eliteCount; e++)
{
int randomIndex = UnityEngine.Random.Range(0, floor.Levels.Count);
if (floor.Levels[randomIndex].Type == FloorType.NormalBattle) // Prevent overriding already elite
{
floor.Levels[randomIndex].Type = FloorType.EliteBattle;
eliteBattlesInRealm--;
}
}
}
realm.Add(floor);
}
string realmName = realmNames[r];
gameStructure.Add(realmName, realm);
realmCompletionAmount.Add(realmName, 0);
}
}
public LevelData GetLevelData(string realmName, int floorIndex, int levelIndex)
{
if (gameStructure.TryGetValue(realmName, out List<FloorData> realm))
{
if (floorIndex >= 0 && floorIndex < realm.Count)
{
FloorData floor = realm[floorIndex];
if (levelIndex >= 0 && levelIndex < floor.Levels.Count)
{
return floor.Levels[levelIndex];
}
}
}
return null;
}
public void UpdateLevelStatus(string realmName, int floorIndex, int levelIndex, bool isUnlocked, bool isCompleted)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
if (level != null)
{
level.IsUnlocked = isUnlocked;
level.IsCompleted = isCompleted;
}
}
public void SetEnteredLevel(string realmName, int floorIndex, int levelIndex)
{
currentLevel = (realmName, floorIndex, levelIndex);
}
public List<LevelData> GetNextLevels(string realmName, int floorIndex, int levelIndex)
{
List<LevelData> nextLevels = new List<LevelData>();
if (gameStructure.TryGetValue(realmName, out var realm))
{
// Check for next level in the same floor
if (levelIndex + 1 < realm[floorIndex].Levels.Count)
{
LevelData nextLevel = realm[floorIndex].Levels[levelIndex + 1];
nextLevels.Add(nextLevel);
}
// If last level in the floor, add levels from the next floor
else if (floorIndex + 1 < realm.Count)
{
var nextFloor = realm[floorIndex + 1];
nextLevels.AddRange(nextFloor.Levels);
}
}
return nextLevels;
}
public void UnlockLevel(string realmName, int floorIndex, int levelIndex)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
if (level != null)
{
level.IsUnlocked = true;
}
}
public bool IsRealmCompleted(string realmName)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
return realm.All(floor => floor.Levels.All(level => level.IsCompleted));
}
return false;
}
public void ResetRealm(string realmName)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
foreach (var floor in realm)
{
foreach (var level in floor.Levels)
{
level.IsUnlocked = false;
level.IsCompleted = false;
}
}
// Unlock the first level of the first floor
if (realm.Count > 0 && realm[0].Levels.Count > 0)
{
realm[0].Levels[0].IsUnlocked = true;
}
// Increment realm completion amount
realmCompletionAmount[realmName]++;
}
}
public void LockLevelsInStep(string realmName, int levelStep)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
foreach (var floor in realm)
{
foreach (var level in floor.Levels)
{
if (level.LevelStep == levelStep && !level.IsCompleted)
{
level.IsUnlocked = false;
}
}
}
}
}
public int GetRealmCompletionAmount(string realmName)
{
if (realmCompletionAmount.TryGetValue(realmName, out int amount))
{
return amount;
}
return 0;
}
public bool IsPreviousLevelCompleted(string realmName, int floorIndex, int levelIndex)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
if (floorIndex > 0)
{
var previousFloor = realm[floorIndex - 1];
return previousFloor.Levels.All(level => level.IsCompleted);
}
else if (levelIndex > 0)
{
return realm[floorIndex].Levels[levelIndex - 1].IsCompleted;
}
}
return true; // First level of the first floor is always considered "unlocked"
}
public FloorType GetFloorType(string realmName, int floorIndex)
{
if (gameStructure.TryGetValue(realmName, out var realm))
{
if (floorIndex >= 0 && floorIndex < realm.Count)
{
return realm[floorIndex].Type;
}
}
return FloorType.NormalBattle; // Default to normal battle if not found
}
// Method to get all levels in a realm
public List<LevelData> GetAllLevelsInRealm(string realmName)
{
List<LevelData> allLevels = new List<LevelData>();
if (gameStructure.TryGetValue(realmName, out var realm))
{
foreach (var floor in realm)
{
allLevels.AddRange(floor.Levels);
}
}
return allLevels;
}
// Method to get the current level data
public LevelData GetCurrentLevelData()
{
return GetLevelData(currentLevel.realm, currentLevel.floor, currentLevel.level);
}
// Method to check if a level is unlocked
public bool IsLevelUnlocked(string realmName, int floorIndex, int levelIndex)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
return level != null && level.IsUnlocked;
}
// Method to get the number of completed levels in a realm
public int GetCompletedLevelCount(string realmName)
{
int count = 0;
if (gameStructure.TryGetValue(realmName, out var realm))
{
count = realm.Sum(floor => floor.Levels.Count(level => level.IsCompleted));
}
return count;
}
// Method to get the total number of levels in a realm
public int GetTotalLevelCount(string realmName)
{
int count = 0;
if (gameStructure.TryGetValue(realmName, out var realm))
{
count = realm.Sum(floor => floor.Levels.Count);
}
return count;
}
// New method to complete a level
public void CompleteLevel(string realmName, int floorIndex, int levelIndex)
{
LevelData level = GetLevelData(realmName, floorIndex, levelIndex);
if (level != null && level.IsUnlocked && !level.IsCompleted)
{
level.IsCompleted = true;
// Unlock the next level
if (levelIndex + 1 < gameStructure[realmName][floorIndex].Levels.Count)
{
UnlockLevel(realmName, floorIndex, levelIndex + 1);
}
else if (floorIndex + 1 < gameStructure[realmName].Count)
{
var nextFloor = gameStructure[realmName][floorIndex + 1];
foreach (var nextLevel in nextFloor.Levels)
{
UnlockLevel(realmName, floorIndex + 1, nextLevel.LevelIndex);
}
}
// Check for realm completion
if (IsRealmCompleted(realmName))
{
Debug.Log($"Realm {realmName} completed!");
// Perform additional actions if needed
}
// Optionally, save the game immediately after completion
// DataPersistenceManager.instance.Save();
}
}
}
Level.cs
using UnityEngine;
using UnityEngine.UI;
public class Level : MonoBehaviour
{
[Header("Level Identification")]
[SerializeField] private string realmName;
[SerializeField] private int floorIndex;
[SerializeField] private int levelIndex;
private Button levelButton;
private Image levelImage;
private void Awake()
{
// Ensure the button and image components are attached
levelButton = GetComponent<Button>();
levelImage = GetComponent<Image>();
if (levelButton == null || levelImage == null)
{
Debug.LogError("Level script requires Button and Image components.");
}
// Set transparency for clickable UI elements
levelImage.alphaHitTestMinimumThreshold = 0.01f;
}
private void Start()
{
UpdateLevelButton();
}
// Updates the visual and interactable state of the level button
private void UpdateLevelButton()
{
LevelData levelData = GameStructureManager.Instance.GetLevelData(realmName, floorIndex, levelIndex);
if (levelData != null)
{
if (levelData.IsUnlocked)
{
if (levelData.IsCompleted)
{
levelButton.interactable = false;
levelImage.color = new Color(0f, 0f, 1f, 0.5f); // Blue with transparency
}
else
{
levelButton.interactable = true;
levelImage.color = new Color(1f, 1f, 1f); // White
}
}
else
{
levelButton.interactable = false;
levelImage.color = new Color(0.5f, 0.5f, 0.5f, 0f); // Grey and transparent
}
}
else
{
// If level data is not found, lock the level
levelButton.interactable = false;
levelImage.color = new Color(0.5f, 0.5f, 0.5f, 0f);
}
}
// Method called when the level button is clicked to load the level
public void LoadLevel(string levelToLoad)
{
Debug.Log($"Loading level: {levelToLoad}");
GameStructureManager.Instance.SetEnteredLevel(realmName, floorIndex, levelIndex);
DataPersistenceManager.instance.LoadSceneAsync(levelToLoad);
}
// Method to mark the level as completed
public void CompleteLevel()
{
GameStructureManager.Instance.CompleteLevel(realmName, floorIndex, levelIndex);
UpdateLevelButton();
}
// Optional: Refresh the level button UI (can be called externally if needed)
public void Refresh()
{
UpdateLevelButton();
}
}
FloorData.cs
using System;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class FloorData
{
public FloorType Type;
public List<LevelData> Levels = new List<LevelData>();
}
LevelData.cs
using System;
using UnityEngine;
[System.Serializable]
public class LevelData
{
public FloorType Type;
public EventType? EventType;
public int EnemyCount;
public int LevelStep;
public bool IsUnlocked;
public bool IsCompleted;
public int FloorIndex;
public int LevelIndex;
}
Recommendations and Best Practices
-
Event Handling: For more dynamic UI updates, consider implementing an event system. The GameStructureManager can trigger events when levels are completed or unlocked, and Level scripts can subscribe to these events to update their UI in real-time.
-
Serialization Considerations: Unity's built-in JsonUtility has limitations with serializing complex data structures like dictionaries and nullable types. Using a more robust JSON library like Newtonsoft.Json can simplify serialization and deserialization processes.
-
UI Feedback: Enhance the user experience by providing visual or audio feedback when levels are unlocked or completed. This can include animations, sound effects, or notifications.
-
Error Handling: Implement comprehensive error handling to manage scenarios where level data might be missing or corrupted. This ensures that your game remains stable and provides informative feedback during unexpected situations.
-
Performance Optimization: If your game has a large number of levels, ensure that the GameStructureManager efficiently manages memory and processing. Lazy loading levels or optimizing data structures can help maintain performance.
-
Testing: Rigorously test the new system to ensure that levels unlock and lock correctly, data persists accurately between sessions, and the UI reflects the correct states.
By centralizing your level management within the GameStructureManager, you create a more maintainable and scalable system. This approach reduces redundancy, simplifies debugging, and enhances the overall structure of your game's logic.
Note: Ensure that all serialized fields are correctly assigned in the Unity Inspector for each level object. Additionally, adapt the DataPersistenceManager as needed to align with your specific data storage and retrieval mechanisms.