Last active
May 3, 2017 14:08
-
-
Save rhys-vdw/d9aa93c5c625a1799ce3ae8a33509c19 to your computer and use it in GitHub Desktop.
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
public interface IPoolStrategy<I> | |
{ | |
void ActivateInstance(I instance); | |
void DeactivateInstance(I instance); | |
I Instantitate(); | |
} | |
public class ToggleActivePoolStrategy<C> : IPoolStrategy<C> where C : Component | |
{ | |
public C Instantiate() | |
{ | |
return Object.Instantiate<C>(_prefab); | |
} | |
public void ActivateInstance(C instance) | |
{ | |
instance.gameObject.SetActive(true); | |
} | |
public void DeactivateInstance(C instance) | |
{ | |
instance.gameObject.SetActive(false); | |
} | |
} | |
// Holds the list of pooled objects. | |
public class Pool<I> | |
{ | |
IPoolStrategy _strategy; | |
Stack<I>[] _pooledInstances; | |
public Pool(IPoolStrategy strategy, IEnumerable<T> instances) | |
{ | |
_strategy = strategy; | |
_pooledInstances = new Stack<I>(instances); | |
for (var i = 0; i < size; i++) | |
{ | |
_strategy.DeactivateInstance(_pooledInstances[i]); | |
} | |
} | |
public I GetInstance() | |
{ | |
if (IsEmpty) | |
{ | |
throw InvalidOperationException("Pool is empty"); | |
} | |
I instance = _pooledInstances.Pop(); | |
_strategy.ActivateInstance(instance); | |
return instance; | |
} | |
public void ReturnInstance(I instance) | |
{ | |
_strategy.DeactivateInstance(instance); | |
_pooledInstances.Push(instance); | |
} | |
public bool IsEmpty | |
{ | |
get { return _pooledInstances.IsEmpty } | |
} | |
} | |
public abstract class InitializingPool<T> : Pool<T> | |
{ | |
InitializingPool(PoolSint size) : | |
{ | |
_pooledInstances = new Stack<I>[size]; | |
for (var i = 0; i < size; i++) | |
{ | |
_pooledInstances[i] = Instantiate(); | |
} | |
base(_pooledInstances); | |
} | |
protected virtual T Instantiate(); | |
} | |
// A layer manager actually using a pool. | |
public class ScrollingLayer : MonoBehaviour | |
{ | |
public int PoolSize; | |
private List<Transform> Instances; | |
public Transform Prefab; | |
void Awake() | |
{ | |
_pool = new ToggleActivePool<Transform>(Prefab, PoolSize); | |
} | |
void Update() | |
{ | |
if (!_pool.IsEmpty && timeToAddACloud) | |
{ | |
_instances.Add(_pool.GetInstance()) | |
} | |
for (var instance in _instances) | |
{ | |
instance.transform += Vector3.right; | |
} | |
// depool any clouds that have fallen out of range... | |
_pool.ReturnInstance(...) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment