Homebound / Scripts / LevelSelector.cs
LevelSelector.cs
Raw
using System.Collections.Generic;
using UnityEngine;

public class LevelSelector : MonoBehaviour, IDDataPersistence
{
    public static LevelSelector Instance { get; private set; }

    [Header("Levels")]
    [SerializeField] List<LevelSO> levels; // List of all of the levels in the game
    List<string> levelsShownToPlayer; // List of levels that will be active for the player to see
    LevelSO completedLevel; // Reference for the level that was completed to be called from the CollisionHandler

    // Trigger for returning in Saving for menu screens when level is not called
    [SerializeField] bool menuScreen = false;

    void Awake()
    {
        Instance = this; // Initializes the Instance
    }

    /// <summary>
    /// A reference for the current level before loading the next level is taken before the game is saved using the 
    /// completed level as reference for the SaveData() below
    /// </summary>
    /// <param name="buildIndex"></param>
    public void LevelCompleted(int buildIndex)
    {
        foreach (LevelSO level in levels)
        {
            if (level.buildIndexRef == buildIndex)
                completedLevel = level;
        }

        if (completedLevel == null)
            return;

        DataPersistenceManager.Instance.SaveGame();
    }

    // Loads Data
    public void LoadData(GameData data)
    {
        levelsShownToPlayer = new(); // Initializes the List to show to the player upon loading

        // Each level is cycle through and added to the levels list that is shown to the player if the level was already completed
        foreach (KeyValuePair<string, bool> level in data.levelsCompleted)
        {
            if (level.Value)
                levelsShownToPlayer.Add(level.Key);
        }
    }

    // Saves Data
    public void SaveData(ref GameData data)
    {
        if (menuScreen) 
            return;

        // Remove the false value for the completed level
        data.levelsCompleted.Remove(completedLevel.levelName);

        // Then re-add the completed level with a true value
        data.levelsCompleted.Add(completedLevel.levelName, true);
    }
}