Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created January 30, 2023 04:59
Show Gist options
  • Save takumifukasawa/1754e65147a120a42345db2b8b92ef0d to your computer and use it in GitHub Desktop.
Save takumifukasawa/1754e65147a120a42345db2b8b92ef0d to your computer and use it in GitHub Desktop.
unity: game object (component) pool
using System.Collections.Generic;
using UnityEngine;
namespace Utilities
{
public class GameObjectPool<T> where T : Component
{
private GameObject _rootObj;
private T _spawnObject;
private int _poolNum;
private int _currentPickIndex = 0;
private List<T> _poolObjects = new List<T>();
public List<T> PoolObjects
{
get => _poolObjects;
}
public GameObject RootObj
{
get => _rootObj;
}
public int PoolNum
{
get => _poolNum;
}
/// <summary>
///
/// </summary>
/// <param name="spawnObject"></param>
/// <param name="poolNum"></param>
/// <param name="parentTransform"></param>
public GameObjectPool(T spawnObject, int poolNum, Transform parentTransform = null)
{
_spawnObject = spawnObject;
_poolNum = poolNum;
_rootObj = new GameObject();
_rootObj.transform.parent = parentTransform;
SpawnObjects();
}
/// <summary>
///
/// </summary>
void SpawnObjects()
{
for (int i = 0; i < _poolNum; i++)
{
var obj = GameObject.Instantiate(_spawnObject);
obj.transform.parent = _rootObj.transform;
_poolObjects.Add(obj);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public T PickObject()
{
if (_poolObjects.Count < 1)
{
return default(T);
}
int index = _currentPickIndex;
_currentPickIndex = (_currentPickIndex + 1) % _poolObjects.Count;
return _poolObjects[index];
}
/// <summary>
///
/// </summary>
public void DestroyObjects()
{
foreach (Transform child in _rootObj.transform)
{
GameObject.Destroy(child.gameObject);
}
}
/// <summary>
///
/// </summary>
public void DestroyPool()
{
GameObject.Destroy(_rootObj);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment