using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;

namespace Utilities
{
    public static class DontDestroyOnLoadUtils
    {
        private static readonly List<GameObject> ManagedObjects = new List<GameObject>();

        public static void Add(GameObject gameObject)
        {
            ManagedObjects.Add(gameObject);
            Object.DontDestroyOnLoad(gameObject);
        }

        public static void DestroyAll(Func<GameObject, bool> filter = null)
        {
            foreach (GameObject managedObject in ManagedObjects.ToList())
            {
                if (filter != null && !filter.Invoke(managedObject))
                    continue;
                
                Object.DestroyImmediate(managedObject);
            }
            ManagedObjects.Clear();
        }
    }
}