using System; using BriarQueen.Framework.Assets; using Cysharp.Threading.Tasks; using UnityEngine; using VContainer; using Object = UnityEngine.Object; namespace BriarQueen.Framework.Services.Destruction { /// /// Handles safe destruction of GameObjects and ensures proper cleanup from world state. /// public class DestructionService { private readonly AddressableManager _addressables; [Inject] public DestructionService(AddressableManager addressables) { _addressables = addressables; } /// /// Asynchronously destroys a GameObject, invoking destructible callbacks and unregistering state. /// public async UniTask Destroy(GameObject go) { if (go == null) return; Debug.Log($"[DestructionManager] Trying to destroy object of {go}"); var destructibles = go.GetComponentsInChildren(true); if (destructibles is { Length: > 0 }) { foreach (var d in destructibles) try { if (d != null) await d.OnPreDestroy(); } catch (Exception ex) { Debug.LogWarning($"[DestructionManager] Exception in OnPreDestroy of {d}: {ex}"); } foreach (var d in destructibles) try { if (d != null) await d.OnDestroyed(); } catch (Exception ex) { Debug.LogWarning($"[DestructionManager] Exception in OnDestroyed of {d}: {ex}"); } } // Prefer Addressables release if this is an Addressables-managed instance. if (_addressables != null && _addressables.TryReleaseInstance(go)) return; // Addressables.ReleaseInstance will destroy it. Object.Destroy(go); } } }