Skip to content

Instantly share code, notes, and snippets.

@runewake2
Created March 1, 2017 06:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runewake2/3a427703b4929a014fa7a83a496cea3c to your computer and use it in GitHub Desktop.
Save runewake2/3a427703b4929a014fa7a83a496cea3c to your computer and use it in GitHub Desktop.
Unity 3D Generic Object Pool for pooling a set object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Creates a cached object pool for reduced memory thrashing.
// Developed as a part of World of Zero, an interactive programming YouTube channel: youtube.com/worldofzerodevelopment
public class GenericObjectPool : MonoBehaviour
{
public int count;
public GameObject prefab;
private int lastSelected = 0;
private GameObject[] instances;
// Use this for initialization
void Start () {
instances = new GameObject[count];
for (int i = 0; i < count; ++i)
{
var instance = Instantiate(prefab);
instance.SetActive(false);
instance.transform.parent = this.transform;
instances[i] = instance;
}
}
public GameObject Instantiate(Vector3 position, Quaternion rotation)
{
for (int i = 0; i < instances.Length; i++)
{
int index = (lastSelected + 1 + i) % instances.Length;
if (!instances[index].activeSelf)
{
lastSelected = index;
instances[index].SetActive(true);
instances[index].transform.position = position;
instances[index].transform.rotation = rotation;
return instances[index];
}
}
return null;
}
public void Destroy(GameObject gameObject)
{
gameObject.SetActive(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment