using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pool : MonoBehaviour {
    

    public GameObject template;

    HashSet<GameObject> activeSet = new HashSet<GameObject>();
    Stack<GameObject> inactiveStack = new Stack<GameObject>();

    public void SetTemplate(GameObject go)
    {
        this.template = go;
    }

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public GameObject Gen()
    {
        if (inactiveStack.Count == 0)
        {
            var go = GameObject.Instantiate(template);
            go.transform.SetParent(transform);
            go.transform.localPosition = Vector3.zero;
            go.SetActive(true);
            activeSet.Add(go);
            return go;
        }
        else
        {
            var go = inactiveStack.Pop();
            go.SetActive(true);
            activeSet.Add(go);
            return go;
        }
    }

    public void Recycle(GameObject go)
    {
        activeSet.Remove(go);
        inactiveStack.Push(go);
        go.SetActive(false);
    }

    public void Clear()
    {
        foreach (var go in activeSet)
        {
            Destroy(go);
        }

        activeSet.Clear();
    }
}
