using System; using System.Collections.Generic; using System.Linq; using UnityEngine;…
- User
using System; using System.Collections.Generic; using System.Linq; using UnityEngine;
public enum FloorType { NormalBattle, EliteBattle, BossBattle, Event }
public enum EventType { Shop, Rest, Blacksmith, RPG }
[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; }
[System.Serializable] public class FloorData { public FloorType Type; public List Levels = new List(); }
public class GameStructureManager : MonoBehaviour { 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); GenerateGameStructure(); } else { Destroy(gameObject); } } 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); floor.Levels[randomIndex].Type = FloorType.EliteBattle; eliteBattlesInRealm--; } } realm.Add(floor); } gameStructure.Add(realmNames[r], realm); realmCompletionAmount.Add(realmNames[r], 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)) { if (floorIndex >= 0 && floorIndex < realm.Count - 1) { 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; }}
i am currently making a unity game in c# and trying to add this file and logic to my existing project. in my current project i have a level script which i have on every level object that decides the status of itself. but with this file and its logic the level system logic is starting to get more central, since before i was getting and calculating each levels status on the level script attached to each level but now the file above has logic for accessing statuses of all levels and i also would like to make it more centralized like this rather than executing 10-15 scripts, here is my current level script as well. what would you recommend and do in my situation and also share the final code files as well thank you.
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Serialization; using UnityEngine.UI;
public class Level : MonoBehaviour, IDataPersistence { [SerializeField] private int levelName; [SerializeField] private int levelStep; [SerializeField] private bool isUnlocked;
public bool IsUnlocked { get => isUnlocked; set => isUnlocked = value; } [SerializeField] private bool isCompleted; [SerializeField] private List<GameObject> nextNeighbors; private static int lastCompleted; private static int enteredLevel; private static int fireCompletionAmount; private void Awake() { levelName = Convert.ToInt32(gameObject.name); GetComponent<Image>().alphaHitTestMinimumThreshold = 0.01f; } private void Start() { if (levelName == 1 && !isCompleted) { isUnlocked = true; } CompleteLevel(); UpdateLevelButton(); } public void LoadData(GameData data) { if (data.fireRealmLevels.TryGetValue(levelName, out int levelStatus)) { isUnlocked = levelStatus != 0; isCompleted = levelStatus == 2; } else { isUnlocked = false; isCompleted = false; } lastCompleted = data.fireLastCompleted; fireCompletionAmount = data.fireCompletionAmount; } public void SaveData(GameData data) { data.fireCompletionAmount = fireCompletionAmount; if (data.fireRealmLevels.ContainsKey(levelName)) { data.fireRealmLevels.Remove(levelName); } data.fireRealmLevels.Add(levelName, isCompleted ? 2 : isUnlocked ? 1 : 0); data.fireLastCompleted = lastCompleted; data.fireEnteredLevel = enteredLevel; } private void UpdateLevelButton() { if (isUnlocked) { if (isCompleted) { GetComponent<Button>().interactable = false; GetComponent<Image>().color = new Color(0f, 0f, 1f, 0.5f); } else { GetComponent<Button>().interactable = true; GetComponent<Image>().color = new Color(1f, 1f, 1f); } } else { GetComponent<Button>().interactable = false; GetComponent<Image>().color = new Color(0.5f, 0.5f, 0.5f, 0f); } } public void LoadLevel(string levelToLoad) { Debug.Log(levelToLoad); enteredLevel = Convert.ToInt32(gameObject.name); DataPersistenceManager.instance.LoadSceneAsync(levelToLoad); } public void CompleteLevel() { if (levelName == lastCompleted) { Level[] levels = FindObjectsOfType<Level>(); if (nextNeighbors.Count == 0) { fireCompletionAmount++; foreach (Level level in levels) { level.isUnlocked = false; level.isCompleted = false; lastCompleted = 0; level.UpdateLevelButton(); } DataPersistenceManager.instance.LoadSceneAsync("RealmSelect"); return; } // logic to lock the levels in the same step, every level has a step written as levelStep integer foreach (Level level in levels) { if (level.levelStep == levelStep && !level.isCompleted) { level.isUnlocked = false; level.UpdateLevelButton(); } } foreach (GameObject neighbor in nextNeighbors) { Level neighborLevel = neighbor.GetComponent<Level>(); neighborLevel.IsUnlocked = true; neighborLevel.UpdateLevelButton(); // Update button state } } }}
- Assistant
Based on your situation, I recommend centralizing the level management using
GameStructureManageras you intended. This approach allows you to manage all level data and logic in a single location rather than having multiple scripts attached to each level object. Here's how you can proceed:-
Replace
Level.cswithLevelButton.cs: Create a new script calledLevelButton.csthat will handle UI interactions for each level button. This script will communicate withGameStructureManagerto get the level's status and update the UI accordingly. -
Implement Data Persistence in
GameStructureManager: ModifyGameStructureManagerto implement theIDataPersistenceinterface. This ensures that all level data is saved and loaded correctly. -
Use Events to Update Level Buttons: In
GameStructureManager, use events to notifyLevelButtoninstances when level statuses change.LevelButtonscripts can subscribe to these events and update their UI accordingly. -
Modify Level Completion Logic: When a player completes a level, notify
GameStructureManagerby calling a method likeLevelCompleted(). The manager will handle unlocking the next levels, locking levels in the same step, and updating level statuses. -
Update the Scene Setup: In your Unity scene, remove the
Level.csscripts from your level UI elements and attach the newLevelButton.csscript instead. Make sure to set therealmName,floorIndex, andlevelIndexin the Inspector for each level button. -
Ensure Consistent Level Data: Make sure that
GameStructureManagerandGameDataclass are updated to handle all realms and levels. Use dictionaries to store level data, and uniquely identify levels using a combination of floor and level indices.
Final Code Files:
LevelButton.cs:
using UnityEngine; using UnityEngine.UI; public class LevelButton : MonoBehaviour { public string realmName; // E.g., "Fire" public int floorIndex; public int levelIndex; private Button button; private Image image; private void Awake() { button = GetComponent<Button>(); image = GetComponent<Image>(); if (button != null) { button.onClick.AddListener(OnLevelButtonClicked); } } private void OnEnable() { if (GameStructureManager.Instance != null) { GameStructureManager.Instance.OnLevelStatusChanged += OnLevelStatusChanged; UpdateLevelButton(); } } private void OnDisable() { if (GameStructureManager.Instance != null) { GameStructureManager.Instance.OnLevelStatusChanged -= OnLevelStatusChanged; } } private void OnLevelStatusChanged(string changedRealmName) { if (realmName == changedRealmName) { UpdateLevelButton(); } } public void UpdateLevelButton() { LevelData levelData = GameStructureManager.Instance.GetLevelData(realmName, floorIndex, levelIndex); if (levelData != null) { if (levelData.IsUnlocked) { if (levelData.IsCompleted) { button.interactable = false; image.color = new Color(0f, 0f, 1f, 0.5f); } else { button.interactable = true; image.color = Color.white; } } else { button.interactable = false; image.color = new Color(0.5f, 0.5f, 0.5f, 0f); } } else { button.interactable = false; image.color = Color.gray; } } private void OnLevelButtonClicked() { GameStructureManager.Instance.SetEnteredLevel(realmName, floorIndex, levelIndex); // Load the level scene // For example: SceneManager.LoadScene("LevelSceneName"); } }GameStructureManager.cs:
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; public enum FloorType { NormalBattle, EliteBattle, BossBattle, Event } public enum EventType { Shop, Rest, Blacksmith, RPG } [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; public string RealmName; } [System.Serializable] public class FloorData { public FloorType Type; public List<LevelData> Levels = new List<LevelData>(); } 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; public delegate void LevelStatusChangedDelegate(string realmName); public event LevelStatusChangedDelegate OnLevelStatusChanged; private void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); GenerateGameStructure(); } else { Destroy(gameObject); } } 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; string realmName = realmNames[r]; 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, RealmName = realmName }; 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); floor.Levels[randomIndex].Type = FloorType.EliteBattle; eliteBattlesInRealm--; } } realm.Add(floor); } 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 LevelData GetCurrentLevelData() { return GetLevelData(currentLevel.realm, currentLevel.floor, currentLevel.level); } public void LevelCompleted() { CompleteLevel(currentLevel.realm, currentLevel.floor, currentLevel.level); } public void CompleteLevel(string realmName, int floorIndex, int levelIndex) { LevelData currentLevelData = GetLevelData(realmName, floorIndex, levelIndex); if (currentLevelData != null && !currentLevelData.IsCompleted) { currentLevelData.IsCompleted = true; // Lock other levels in the same step if they are not completed LockLevelsInStep(realmName, currentLevelData.LevelStep); // Unlock next levels List<LevelData> nextLevels = GetNextLevels(realmName, floorIndex, levelIndex); foreach (var level in nextLevels) { if (!level.IsCompleted) { level.IsUnlocked = true; } } // Check if realm is completed if (IsRealmCompleted(realmName)) { realmCompletionAmount[realmName]++; // Reset the realm for replay ResetRealm(realmName); // Load realm selection scene SceneManager.LoadScene("RealmSelect"); return; } // Notify LevelButtons to update OnLevelStatusChanged?.Invoke(realmName); } } public List<LevelData> GetNextLevels(string realmName, int floorIndex, int levelIndex) { List<LevelData> nextLevels = new List<LevelData>(); if (gameStructure.TryGetValue(realmName, out var realm)) { if (floorIndex >= 0 && floorIndex < realm.Count - 1) { 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]++; // Notify LevelButtons to update OnLevelStatusChanged?.Invoke(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; } } } // Notify LevelButtons to update OnLevelStatusChanged?.Invoke(realmName); } } public void LoadData(GameData data) { // Load realm levels statuses foreach (var realmEntry in data.realmLevels) { string realmName = realmEntry.Key; Dictionary<string, int> levelStatuses = realmEntry.Value; if (gameStructure.TryGetValue(realmName, out List<FloorData> realm)) { foreach (var floor in realm) { foreach (var level in floor.Levels) { string levelKey = $"{level.FloorIndex}-{level.LevelIndex}"; if (levelStatuses.TryGetValue(levelKey, out int status)) { level.IsUnlocked = status >= 1; level.IsCompleted = status == 2; } } } } } realmCompletionAmount = data.realmCompletionAmount; } public void SaveData(GameData data) { if (data.realmLevels == null) { data.realmLevels = new Dictionary<string, Dictionary<string, int>>(); } data.realmLevels.Clear(); foreach (var realmEntry in gameStructure) { string realmName = realmEntry.Key; List<FloorData> realm = realmEntry.Value; Dictionary<string, int> levelStatuses = new Dictionary<string, int>(); foreach (var floor in realm) { foreach (var level in floor.Levels) { string levelKey = $"{level.FloorIndex}-{level.LevelIndex}"; int status = level.IsCompleted ? 2 : level.IsUnlocked ? 1 : 0; levelStatuses[levelKey] = status; } } data.realmLevels[realmName] = levelStatuses; } data.realmCompletionAmount = new Dictionary<string, int>(realmCompletionAmount); } }GameData.cs:
using System.Collections.Generic; [System.Serializable] public class GameData { public Dictionary<string, Dictionary<string, int>> realmLevels = new Dictionary<string, Dictionary<string, int>>(); public Dictionary<string, int> realmCompletionAmount = new Dictionary<string, int>(); public GameData() { realmLevels = new Dictionary<string, Dictionary<string, int>>(); realmCompletionAmount = new Dictionary<string, int>(); } }Summary of Changes:
-
Centralized Level Management: All level data and logic are now centralized in
GameStructureManager. This makes it easier to manage and maintain levels across your entire game. -
LevelButton Interaction: The
LevelButtonscript handles UI interactions and updates the button visuals based on the level's status fetched fromGameStructureManager. -
Data Persistence:
GameStructureManagernow handles loading and saving all level statuses, ensuring persistent game progress. -
Event System for UI Updates: An event system is used to notify
LevelButtoninstances whenever there's a change in level statuses, ensuring the UI is always up-to-date.
Next Steps:
-
Update the Unity Scenes: Remove the old
Level.csscript from your level UI elements and attach the newLevelButton.csscript. Set therealmName,floorIndex, andlevelIndexfor each level button in the Inspector. -
Adjust Level Completion Logic: In your level scenes, ensure that when a player completes a level, you call
GameStructureManager.Instance.LevelCompleted();. -
Test Thoroughly: Since this is a significant change, thoroughly test all aspects of level progression, data saving/loading, and UI updates to ensure everything works as expected.
By centralizing your level logic, you'll have a more maintainable and scalable system, reducing the need for multiple scripts and making it easier to implement new features in the future.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.