﻿using UnityEngine;

namespace AsmodeeDigital.Common.Plugin.Utils
{
    /// <summary>
    /// Dont destroy object in Unity's hierarchy and keep only the first instance. Useful for singletons
    /// </summary>
    public class Singleton : MonoBehaviour
    {
        private static Singleton _instance;

        void Awake()
        {
            DontDestroyOnLoad(this.gameObject);

            if(_instance != null)
            {
                //--- Destroy other copy of the manager
                Singleton[] instances = GameObject.FindObjectsOfType<Singleton>();

                if (instances.Length > 1)
                {
                    foreach (Singleton instance in instances)
                    {
                        if (_instance != instance)
                            GameObject.Destroy(instance.gameObject);
                    }
                }
                //---
            }
            else
            {
                _instance = this;
            }
        }
    }
}
