Skip to content

Instantly share code, notes, and snippets.

@smkplus
Created July 25, 2019 04:03
Show Gist options
  • Save smkplus/aa36826ee15c8b1fb5bd104bd595cd24 to your computer and use it in GitHub Desktop.
Save smkplus/aa36826ee15c8b1fb5bd104bd595cd24 to your computer and use it in GitHub Desktop.
Object Pooling
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TrashMan : MonoBehaviour
{
	/// <summary>
	/// ایجاد کردن پول
	/// </summary>
	/// <param name="obj"></param>
	/// <param name="pos"></param>
    public void PoolInstance(GameObject obj, Transform pos)
    {

        if (IsTrashEmpty())
        {
        var spawn = Instantiate(obj);
        spawn.transform.SetParent(transform);
        }
		UsePool(obj,pos);
    }
	/// <summary>
	/// آیا سطل آشغال پره؟
	/// </summary>
	/// <returns></returns>
    public bool IsTrashEmpty()
    {
        return transform.childCount == 0;
    }
    public void UsePool(GameObject obj, Transform pos)
    {
        transform.GetChild(0).transform.SetParent(pos);
    }
	/// <summary>
	/// بنداز تو سطل آشغال
	/// </summary>
	/// <param name="obj"></param>
    public void BackToPool(Transform obj)
    {
        obj.transform.SetParent(transform);
    }

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

public class Test : MonoBehaviour
{
    public TrashMan trashMan;
    public GameObject prefab;



    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            trashMan.PoolInstance(prefab,transform);

        }

        if (Input.GetKeyDown(KeyCode.T))
        {
            Debug.Log(transform.childCount);
            List<Transform> Temp = new List<Transform>();
            for (int i = 0; i < transform.childCount; i++)
            {
                Temp.Add(transform.GetChild(i));
            }
            Temp.ForEach(x => trashMan.BackToPool(x));
            Temp.Clear();
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment