Skip to content

Instantly share code, notes, and snippets.

@Leopotam
Created April 4, 2019 14:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leopotam/2c17882a56336365f00313c1e6f3803a to your computer and use it in GitHub Desktop.
Save Leopotam/2c17882a56336365f00313c1e6f3803a to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
namespace Client.Common {
sealed class PrefabPool<T> : IDisposable where T : Component {
T[] _items = new T[8];
int _itemsCount;
T _prefab;
public PrefabPool (string prefabPath) {
_prefab = Resources.Load<T> (prefabPath);
}
public T Get () {
bool isNew;
return Get (out isNew);
}
public T Get (out bool isNew) {
return Get (out isNew, Vector3.zero, Quaternion.identity);
}
public T Get (out bool isNew, Vector3 position, Quaternion rotation) {
if (_itemsCount > 0) {
isNew = false;
var item = _items[--_itemsCount];
if (position.sqrMagnitude != 0.0f) {
item.gameObject.transform.position = position;
}
if (rotation != Quaternion.identity) {
item.gameObject.transform.rotation = rotation;
}
return item;
}
isNew = true;
return UnityEngine.Object.Instantiate (_prefab, position, rotation).GetComponent<T> ();
}
public void Recycle (T item) {
if (_items.Length == _itemsCount) {
Array.Resize (ref _items, _itemsCount << 1);
}
_items[_itemsCount++] = item;
}
public void Dispose () {
_prefab = null;
for (var i = 0; i < _itemsCount; i++) {
if (_items[i]) {
UnityEngine.Object.Destroy (_items[i].gameObject);
}
_items[i] = null;
}
_itemsCount = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment