Skip to content

Instantly share code, notes, and snippets.

@hammanandre
Last active June 6, 2018 19:11
Show Gist options
  • Save hammanandre/62429af73ef08db368c874bb726d6a33 to your computer and use it in GitHub Desktop.
Save hammanandre/62429af73ef08db368c874bb726d6a33 to your computer and use it in GitHub Desktop.
An Object pool setup for Unity. Includes some workarounds and awkward phrasings to make Unity friendly.
public interface IPoolable
{
/// <summary>
/// Called when Gotten from Pool
/// </summary>
void Get();
/// <summary>
/// Called when Released to Pool
/// </summary>
void Release();
}
using UnityEngine;
using System.Collections.Concurrent;
public class ObjectPoolFactory<T> where T : IPoolable, new()
{
/// <summary>
/// Collection of Objects
/// </summary>
private readonly ConcurrentBag<IPoolable> Pool = new ConcurrentBag<IPoolable>();
private int count = 0;
private int max;
public virtual IPoolable Get()
{
IPoolable obj;
if (Pool.TryTake(out obj))
{
count--;
obj.Get();
return obj;
}
else
{
obj = new T();
obj.Get();
return obj;
}
}
public virtual void Release(IPoolable obj)
{
if (count < max || max == 0)
{
Pool.Add(obj);
count++;
obj.Release();
}
else
{
Debug.LogError(this + " Exceeds max poolables");
}
}
public ObjectPoolFactory(int Max)
{
this.max = Max;
count = 0;
Pool = new ConcurrentBag<IPoolable>();
}
/// <summary>
/// Maximum amount of Objects in Pool
/// </summary>
public virtual int Max
{
set { max = value; }
}
/// <summary>
/// Current amount of Objects in Pool
/// </summary>
public virtual int Count
{
get { return count; }
}
}
/// <summary>
/// An Object pool that requires the First Generic to inhert or implement the Second Generic
/// </summary>
public class ObjectPoolFactory<T, T2> where T : IPoolable, T2, new()
{
/// <summary>
/// Collection of Objects
/// </summary>
private readonly ConcurrentBag<IPoolable> Pool = new ConcurrentBag<IPoolable>();
private int count = 0;
private int max;
public virtual IPoolable Get()
{
IPoolable obj;
if (Pool.TryTake(out obj))
{
count--;
obj.Get();
return obj;
}
else
{
obj = new T();
obj.Get();
return obj;
}
}
public virtual void Release(IPoolable obj)
{
if (count < max || max == 0)
{
Pool.Add(obj);
count++;
obj.Release();
}
else
{
Debug.LogError(this + " Exceeds max poolables");
}
}
public ObjectPoolFactory(int Max)
{
this.max = Max;
count = 0;
Pool = new ConcurrentBag<IPoolable>();
}
/// <summary>
/// Maximum amount of Objects in Pool
/// </summary>
public virtual int Max
{
set { max = value; }
}
/// <summary>
/// Current amount of Objects in Pool
/// </summary>
public virtual int Count
{
get { return count; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment