Last active
July 10, 2023 17:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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