Created
March 1, 2017 06:23
-
-
Save runewake2/3a427703b4929a014fa7a83a496cea3c to your computer and use it in GitHub Desktop.
Unity 3D Generic Object Pool for pooling a set object.
This file contains hidden or 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; | |
// 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