using System; using System.Collections; using System.Collections.Generic; using PixelCrushers; using UnityEngine; using UnityEngine.Events; namespace Beyond { public class KillTrigger : Saver { [SerializeField] EnemySpawner[] m_spawners; public UnityEvent OnTrigger; [Serializable] public class SaveData { public bool wasTriggered = false; } private SaveData m_data = new SaveData(); void Start() { if (m_spawners == null) return; // Guard clause foreach (var s in m_spawners) { if (s != null) // Good practice to check for null spawners in array { s.m_OnDead.AddListener(OnEnemyKilled); } } } public void CheckSpawners() { if (m_data.wasTriggered) return; if (m_spawners == null) return; // Guard clause foreach (var spawner in m_spawners) { if (spawner == null) continue; // Skip if a spawner in the array is null bool hasSpawnedAWave = spawner.GetWavesSpawnedCount() > 0; // We'll need to add this getter to EnemySpawner bool noEnemiesCurrentlyAlive = !spawner.IsAnyEnemyAlive(); if (hasSpawnedAWave && noEnemiesCurrentlyAlive) { // This spawner has done its part for *this current engagement* } else { return; // If ANY spawner doesn't meet this, the trigger condition isn't met } } OnTrigger?.Invoke(this); m_data.wasTriggered = true; } private void OnEnemyKilled(EnemySpawner arg0) { // arg0 is the spawner from which an enemy died. // We need to check all spawners associated with this trigger. CheckSpawners(); } private void OnDestroy() { if (m_spawners == null) return; // Guard clause foreach (var s in m_spawners) { if (s != null) // Good practice { s.m_OnDead.RemoveListener(OnEnemyKilled); } } } public override string RecordData() { return SaveSystem.Serialize(m_data); } public override void ApplyData(string s) { var data = SaveSystem.Deserialize(s); if (data != null) m_data = data; // Optional: if not triggered, re-check on load in case state was met while inactive // if (!m_data.wasTriggered) { CheckSpawners(); } } } }