Skip to content

Instantly share code, notes, and snippets.

@belzecue
Created August 24, 2018 11:22
Show Gist options
  • Save belzecue/60ce665f160fb504d05494137c9130f3 to your computer and use it in GitHub Desktop.
Save belzecue/60ce665f160fb504d05494137c9130f3 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ObjectPool : Singleton<ObjectPool>
{
public int StartCount = 10;
public GameObject[] Prefabs;
private readonly List<GameObject> available = new List<GameObject>();
void Start()
{
foreach (GameObject prefab in Prefabs)
{
for (int i = 0; i < StartCount; i++)
{
GameObject go = CreateNewOne(prefab);
available.Add(go);
}
}
}
public GameObject TakeObject(System.Type type)
{
List<Component> components = new List<Component>();
foreach (GameObject gm in available)
{
Component component = gm.GetComponent(type);
if (component != null)
{
components.Add(component);
}
}
GameObject go;
if (components.Count == 0)
{
go = CreateNewOne(type);
}
else
{
go = components[0].gameObject;
available.Remove(go);
}
return go;
}
public void PutObject(GameObject go)
{
go.SetActive(false);
go.transform.position = Vector3.zero;
go.transform.rotation = Quaternion.identity;
go.transform.parent = this.transform;
StartCoroutine("SetAvailable", go);
}
private IEnumerator SetAvailable(GameObject go)
{
yield return new WaitForSeconds(1);
available.Add(go);
}
private GameObject CreateNewOne(GameObject prefab)
{
GameObject go = (GameObject) Instantiate(prefab, Vector3.zero, Quaternion.identity);
go.SetActive(false);
go.transform.parent = this.transform;
return go;
}
private GameObject CreateNewOne(System.Type type)
{
foreach (GameObject go in Prefabs)
{
Component component = go.GetComponent(type);
if (component != null)
{
return CreateNewOne(go.gameObject);
}
}
Debug.LogError("no prefab with type " + type.Name + " found!");
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment