Skip to content

Instantly share code, notes, and snippets.

@NotYannis
Created April 12, 2018 08:27
Show Gist options
  • Save NotYannis/a67650f3a17b851e79695d89ea0399e8 to your computer and use it in GitHub Desktop.
Save NotYannis/a67650f3a17b851e79695d89ea0399e8 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooled : MonoBehaviour
{
public static ObjectPooled current;
public GameObject pooledObject;
public int pooledAmount = 20;
public bool willGrow = true;
List<GameObject> pooledObjects;
private void Awake ()
{
current = this;
}
// Use this for initialization
void Start ()
{
pooledObjects = new List<GameObject>();
for (int i = 0; i < pooledAmount; ++i)
{
GameObject obj = (GameObject)Instantiate(pooledObject, transform);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject ()
{
for (int i = 0; i < pooledObjects.Count; ++i)
{
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
if (willGrow)
{
GameObject obj = (GameObject)Instantiate(pooledObject, transform);
pooledObjects.Add(obj);
return obj;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment