Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions Utils/ObjectPool.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using UnityEngine;

namespace DUCK.Pooling
{
public static class ObjectPool
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few comments documenting how the pool works, when it should be used and any pitfalls would be good.

Part of those comments might be a some a warning against blind or excessive usage of a pool which could cause (assumption alert!) slow down of the GC or creating a large memory footprint and all the usual issues with premature optimisation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to keep this relatively lightweight, so the pools aren't even created until you call ObjectPool.Instantiate - this will create and maintain a pool for the objects to return to when soft-destroyed via ObjectPool.Destroy, but is otherwise transparently identical to the standard Instantiate and Destroy functions, in that they're called as fallbacks if there isn't a pool to use.

I will, though, add guards to prevent a pooled object being pooled a second time, and to prevent the pool from returning destroyed objects, since it's still possible to hard-Destroy something while it's in the pool.

{
private interface Pool
{
Type ObjectType { get; }

void Add(PoolableObject obj);
}

private class Pool<T> : Pool
where T : PoolableObject
{
private Queue<T> pooledObjects = new Queue<T>();

public Type ObjectType
{
get
{
return typeof(T);
}
}

public T Get()
{
var obj = (pooledObjects.Count > 0)
? pooledObjects.Dequeue()
: null;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be worth considering letting the pool manage object creation as well since it handles the other end of the lifecycle and would be much more convenient for the end user.

Its not unusual for pools to return a new instance of the object where you have null if you think that would be less intuitive then a GetOrCreate() method would work.

Copy link
Copy Markdown
Contributor Author

@DSDubit DSDubit Mar 21, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does - ObjectPool is a private class so this will never be called by the end user. See the static Instantiate functions which are for external use - is that not what you mean? They perform the 'create or retrieve' step, either from a prefab or resourcePath


if (obj)
{
obj.RemoveFromPool();
}

return obj;
}

public void Add(PoolableObject obj)
{
if (obj != null)
{
obj.AddToPool();
pooledObjects.Enqueue((T)obj);
}
}
}

private static Dictionary<Type, Pool> poolLookup = new Dictionary<Type, Pool>();

public static T Instantiate<T>(T original = null) where T : PoolableObject
{
T obj = null;

if (PoolExists(typeof(T)))
{
obj = GetFromPool<T>();

if (obj != null)
{
if (original != null)
{
obj.CopyFrom(original);
}

return obj;
}
}
else
{
CreatePool<T>();
}

return obj ?? GameObject.Instantiate<T>(original);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either line 72 needs removing or this line needs to be return GameObject.Instantiate<T>(original);. The reference to obj will always be null if the program reaches here.

}

public static T Instantiate<T>(string resourcePath) where T : PoolableObject
{
T obj = null;

if (PoolExists(typeof(T)))
{
obj = GetFromPool<T>();
}
else
{
CreatePool<T>();
}

return obj ?? Resources.Load<T>(resourcePath);
}

public static void Destroy(PoolableObject obj)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When an object is released to a pool it would be good to invoke a cleanup step.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What would you be cleaning up? PoolableObject already expoded AddedToPool and RemovedFromPool events for any components on the gameObject to listen for - this is where I'd expect custom cleanup actions to take place

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd be cleaning up events :) and state. I didn't spot those add and remove methods though.

Not sure if publicly subscribe-able events will eventually prove problematic in a system that is dealing with objects that at any given time can be hard or soft destroyed.

{
if (obj == null) return;

if (PoolExists(obj.GetType()))
{
ReturnToPool(obj);
}
else
{
Destroy(obj);
}
}

private static void CreatePool<T>() where T : PoolableObject
{
if (PoolExists(typeof(T))) return;

poolLookup.Add(typeof(T), new Pool<T>());
}

private static Pool<T> FindPool<T>() where T : PoolableObject
{
if (!PoolExists(typeof(T))) throw new KeyNotFoundException(typeof(T).ToString());

return (Pool <T>)poolLookup[typeof(T)];
}

private static bool PoolExists(Type type)
{
return poolLookup.ContainsKey(type);
}

private static T GetFromPool<T>() where T : PoolableObject
{
return PoolExists(typeof(T))
? FindPool<T>().Get()
: null;
}

private static void ReturnToPool(PoolableObject obj)
{
if (!PoolExists(obj.GetType())) return;

poolLookup[obj.GetType()].Add(obj);
}
}
}
13 changes: 13 additions & 0 deletions Utils/ObjectPool.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions Utils/PoolableObject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using DUCK.Utils;
using System;
using UnityEngine;

namespace DUCK.Pooling
{
public class PoolableObject : MonoBehaviour
Copy link
Copy Markdown

@pmead pmead Mar 21, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor bit of weirdness, PoolableObject inherits MonoBehaviour but this whole feature references objects as if that's the class you're dealing with but object is a little further up the inheritance tree.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't follow - where does the ObjectPool reference objects as object/Object?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the naming convention.

{
public event Action OnAddedToPool;
public event Action OnRemovedFromPool;

public void AddToPool()
{
OnAddedToPool.SafeInvoke();
}

public void RemoveFromPool()
{
OnRemovedFromPool.SafeInvoke();
}

public void CopyFrom(PoolableObject instance) { }
Copy link
Copy Markdown

@pmead pmead Mar 21, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this needed? To avoid specifically being able to copy a camera?

I'd expect CopyFrom to work but to interact with the pool.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No - to mimic the behaviour of Unity's Instantiate(T original) - see ObjectPool.cs:67

Copy link
Copy Markdown

@pmead pmead Mar 22, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case it might be worth making this abstract or throw. Right now if I'm meant to expect pool.Instantiate(someObject); to work out of the box I may not know that I need to implement my own CopyFrom.

Especially given that sometimes (with the null coalescing) its going to use the original and working GameObject.Inantiate(original);

}
}
13 changes: 13 additions & 0 deletions Utils/PoolableObject.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.