You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
CrowdControl/Assets/Scripts/Utils/LevelsSwitcher.cs

95 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using D2D.Core;
using D2D.Databases;
using D2D.Utilities;
using UnityEngine;
using static D2D.Utilities.SettingsFacade;
using static D2D.Utilities.CommonLazyFacade;
using static D2D.Utilities.CommonGameplayFacade;
namespace D2D
{
[DefaultExecutionOrder(-99)]
public class LevelsSwitcher : GameStateMachineUser
{
[Tooltip("-1 for random")]
[SerializeField] private int _debugCurrentLevel = -1;
[Space]
[Tooltip("To skip for instance 1 level (on loop) put value to 2")]
[SerializeField] private int _minRepeatLevel = 1;
[Tooltip("Just be sure that all passed level switchers have different names")]
[SerializeField] private string _uniqueContainerName = "Levels";
private DataContainer<int> _lastLoadedLevelIndex;
private DataContainer<bool> _isLastLevelWin;
private int currentLevelIndex = 0; // Track the current level index
protected override void OnEnable()
{
base.OnEnable();
if (_gameData.levels.IsNullOrEmpty())
return;
if (_debugCurrentLevel >= 0)
{
Instantiate(_gameData.levels[_debugCurrentLevel - 1]);
return;
}
var id = _uniqueContainerName;
_lastLoadedLevelIndex = new DataContainer<int>("LastShuffledIndex" + id, -1);
_isLastLevelWin = new DataContainer<bool>("IsLastLevelWin" + id, true);
if (!_isLastLevelWin.Value && _lastLoadedLevelIndex.Value > -1)
{
Instantiate(_gameData.levels[_lastLoadedLevelIndex.Value]);
}
else
{
LoadLevel(currentLevelIndex);
}
_isLastLevelWin.Value = false;
}
// Method to load the level based on the current index
private void LoadLevel(int index)
{
try
{
Instantiate(_gameData.levels[index]);
_lastLoadedLevelIndex.Value = index;
Debug.Log($"Loaded level: {index}");
}
catch (Exception e)
{
Debug.LogError(e);
Instantiate(_gameData.levels.GetRandomElement());
}
}
// Method to handle button click to switch to the next level
public void OnNextLevelButtonClick()
{
currentLevelIndex++; // Increment the level index
// Ensure the level index is within bounds
if (currentLevelIndex >= _gameData.levels.Count)
{
currentLevelIndex = _minRepeatLevel - 1; // Reset to the first repeatable level
}
LoadLevel(currentLevelIndex); // Load the next level
}
protected override void OnGameWin()
{
_isLastLevelWin.Value = true;
}
}
}