2025-08-22 20:43:18 +05:00

109 lines
2.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level1 : Level
{
[Header("Enemy Setup")]
[Tooltip("Optional: parent whose children have EnemyBase components")]
public Transform enemiesParent;
[Tooltip("Or manually assign enemies here")]
public List<EnemyBase> enemies = new List<EnemyBase>();
[Header("Monitoring")]
[Tooltip("How often to check alive enemies")]
public float checkInterval = 0.25f;
private bool _running;
private Coroutine _monitorCo;
public override void OnLevelStart()
{
base.OnLevelStart();
// Collect enemies if using a parent
if (enemiesParent != null)
{
enemies.Clear();
foreach (Transform child in enemiesParent)
{
var eb = child.GetComponent<EnemyBase>();
if (eb != null) enemies.Add(eb);
}
}
// Turn enemies on & let their own Start() find the player
foreach (var e in enemies)
{
if (e == null) continue;
e.gameObject.SetActive(true);
}
// Edge case: no enemies -> complete immediately
if (CountAlive() == 0)
{
CompleteLevel();
return;
}
_running = true;
_monitorCo = StartCoroutine(MonitorEnemies());
Debug.Log("Level1: Started, monitoring enemies...");
}
public override void OnLevelEnd()
{
base.OnLevelEnd();
_running = false;
if (_monitorCo != null)
{
StopCoroutine(_monitorCo);
_monitorCo = null;
}
}
private IEnumerator MonitorEnemies()
{
var wait = new WaitForSeconds(checkInterval);
while (_running)
{
if (CountAlive() == 0)
{
CompleteLevel();
yield break;
}
yield return wait;
}
}
private int CountAlive()
{
int alive = 0;
for (int i = 0; i < enemies.Count; i++)
{
var e = enemies[i];
if (e != null && e.gameObject.activeInHierarchy && !e.IsDead())
alive++;
}
return alive;
}
private void CompleteLevel()
{
Debug.Log("Level1: All enemies defeated. Completing level.");
_running = false;
// Tell GameplayManager if available
if (GameplayManager.Instance != null)
{
GameplayManager.Instance.CompleteCurrentLevel();
}
else
{
// Fallback: just disable this level object
gameObject.SetActive(false);
}
}
}