Files

64 lines
2.1 KiB
C#

using System;
using BriarQueen.Framework.Assets;
using Cysharp.Threading.Tasks;
using UnityEngine;
using VContainer;
using Object = UnityEngine.Object;
namespace BriarQueen.Framework.Services.Destruction
{
/// <summary>
/// Handles safe destruction of GameObjects and ensures proper cleanup from world state.
/// </summary>
public class DestructionService
{
private readonly AddressableManager _addressables;
[Inject]
public DestructionService(AddressableManager addressables)
{
_addressables = addressables;
}
/// <summary>
/// Asynchronously destroys a GameObject, invoking destructible callbacks and unregistering state.
/// </summary>
public async UniTask Destroy(GameObject go)
{
if (go == null) return;
Debug.Log($"[DestructionManager] Trying to destroy object of {go}");
var destructibles = go.GetComponentsInChildren<IDestructible>(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);
}
}
}