Skip to content

Instantly share code, notes, and snippets.

@nipundavid
Last active July 10, 2023 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nipundavid/f5fa09f444ebe417ccd6d72e37ac89a3 to your computer and use it in GitHub Desktop.
Save nipundavid/f5fa09f444ebe417ccd6d72e37ac89a3 to your computer and use it in GitHub Desktop.
Gist to create a pool of chickens in Unity3D with the help of object pooling pattern
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChickenPoolController : MonoBehaviour
{
// holds the pool of chickens
private List<Chicken> chickenPool = new List<Chicken>();
// Size of the pool
[SerializeField]
private int chickenPoolSize = 100;
// actual chicken that is part of the pool
public Chicken chickenPrefab;
// Start is called before the first frame update
void Start()
{
// filling the pool with chickens
for (int i = 0; i < chickenPoolSize; i++)
{
// create object of chicken
Chicken chickenObject = Instantiate(chickenPrefab);
// put chicken in list i.e pool
chickenPool.Add(chickenObject);
}
}
/// <summary>
/// get on chicken from pool
/// </summary>
/// <returns></returns>
public Chicken GetChicken()
{
for (int i = 0; i < chickenPoolSize; i++)
{
if(!chickenPool[i].isActiveAndEnabled)
{
return chickenPool[i];
}
}
return null;
}
// Update is called once per frame
void Update()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment