Last active
October 31, 2016 17:09
-
-
Save quabug/3e8689bb20fc163fbb9bdaa094f4e21d to your computer and use it in GitHub Desktop.
This file contains 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; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using Zenject; | |
public interface IRecyclableObject | |
{ | |
GameObject GameOjbect { get; } | |
void Reset(); | |
void Recycle(); | |
void Destroy(); | |
} | |
public interface IRecyclableObject<T> : IRecyclableObject where T : IRecyclableObject<T> | |
{ | |
ObjectPool<T> Pool { get; set; } | |
} | |
public class ObjectPool<T> where T : IRecyclableObject<T> | |
{ | |
private ILogger _logger; | |
private int _maxObject; | |
private Func<T> _createFunc; | |
private readonly Stack<T> _pool = new Stack<T>(); | |
private GameObject _root; | |
public ObjectPool(Func<T> createFunc, int maxObject, ILogger logger) | |
{ | |
_maxObject = maxObject; | |
_logger = logger; | |
_createFunc = createFunc; | |
// HACK: get or create root of pooled object. | |
_root = GameObject.Find("ObjectPool") ?? new GameObject("ObjectPool"); | |
} | |
public T Spawn() | |
{ | |
var recyclable = _pool.Count > 0 ? _pool.Pop() : _createFunc(); | |
recyclable.Pool = this; | |
recyclable.Reset(); | |
return recyclable; | |
} | |
public void Recycle(T recyclable) | |
{ | |
if (recyclable.Pool != this) | |
{ | |
_logger.Log(LogType.Warning, "Pool is not match"); | |
recyclable.Recycle(); | |
return; | |
} | |
if (_pool.Count >= _maxObject) | |
{ | |
recyclable.Destroy(); | |
} | |
else | |
{ | |
recyclable.GameOjbect.transform.SetParent(_root.transform, false); | |
_pool.Push(recyclable); | |
} | |
} | |
} |
This file contains 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 UnityEngine; | |
public abstract class RecyclableComponent<T> : MonoBehaviour, IRecyclableObject<T> where T : IRecyclableObject<T> | |
{ | |
public GameObject GameOjbect { get { return gameObject; } } | |
public abstract void Recycle(); | |
public void Destroy() { GameObject.Destroy(gameObject); } | |
public ObjectPool<T> Pool { get; set; } | |
public virtual void Reset() | |
{ | |
transform.SetParent(null); | |
transform.localPosition = Vector3.zero; | |
transform.localScale = Vector3.one; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment