https://github.com/mackysoft/xpool
Object pooling system for Unity.
https://github.com/mackysoft/xpool
collection csharp fast objectpool pool pooling unity
Last synced: 10 months ago
JSON representation
Object pooling system for Unity.
- Host: GitHub
- URL: https://github.com/mackysoft/xpool
- Owner: mackysoft
- License: mit
- Created: 2022-01-30T04:56:34.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2023-08-20T03:48:05.000Z (over 2 years ago)
- Last Synced: 2025-03-23T20:22:39.686Z (10 months ago)
- Topics: collection, csharp, fast, objectpool, pool, pooling, unity
- Language: C#
- Homepage: https://mackysoft.github.io/XPool/
- Size: 927 KB
- Stars: 71
- Watchers: 2
- Forks: 5
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# XPool - Object Pooling System for Unity
[](https://github.com/mackysoft/XPool/actions/workflows/tests.yaml) [](https://github.com/mackysoft/XPool/actions/workflows/build.yaml) [](https://github.com/mackysoft/XPool/releases) [](https://openupm.com/packages/com.mackysoft.xpool/)

**Created by Hiroya Aramaki ([Makihiro](https://twitter.com/makihiro_dev))**
## What is XPool ?
XPool is an object pooling library for Unity.
This was developed to be able to do all the pooling expected in application development with just this library.
- All your classes can be pooled.
- Short code, easy to use.
- Fast performance
- Scalability
- Tested. It works stably.
- [📥 Installation](#installation)
- [🔰 Usage](#usage)
- [Unity Object Pool](#unity-object-pool)
- [ParticleSystem Pool](#particle-system-pool)
- [Pure C# Object Pool](#object-pool)
- [Collection Pool](#collection-pool)
- [Non Allocated Collections](#non-allocated-collections)
- [How to write custom pool ?](#how-to-write-custom-pool)
- [ParticleSystemPool implementation](#particle-system-pool-implementation)
- [Optimization](#optimization)
- [✉ Help & Contribute](#help-and-contribute)
- [📔 Author Info](#author-info)
- [📜 License](#license)
Download any version from releases.
Releases: https://github.com/mackysoft/XPool/releases
### Install via PackageManager
Or, you can add this package by opening PackageManager and entering
`https://github.com/mackysoft/XPool.git?path=Assets/MackySoft/MackySoft.XPool`
from the `Add package from git URL` option.
### Install via Open UPM
Or, you can install this package from the [Open UPM](https://openupm.com/packages/com.mackysoft.xpool/) registry.
More details [here](https://openupm.com/).
```
openupm add com.mackysoft.xpool
```
# 🔰 Usage
The full Scripting API is [here](https://mackysoft.github.io/XPool/api/MackySoft.XPool.html).
Scripting API: https://mackysoft.github.io/XPool/api/MackySoft.XPool.html
## Unity Object Pool (GameObject, Component)
Pooling of Unity Object (GameObject, Component) can be performed using `GameObjectPool` or `ComponentPool`.
These hierarchical objects can be rented by writing them in a similar way to `Instantiate` method.
```cs
// Example code is being written...
```
Optimized pools are available for some of the components implemented in Unity.
This is an example of `ParticleSystemPool` usage.
```cs
public class HitParticleSystemEmitter : MonoBehaviour {
[SerializeField]
ParticleSystemPool m_HitParticleSystemPool = new ParticleSystemPool();
void OnCollisionEnter (Collision collision) {
// The rented ParticleSystem is automatically returned to the pool when completed.
m_HitParticleSystemPool.Rent(collision.contacts[0],Quaternion.identity);
}
}
```
If you need an optimized pool for other components, please refer to the [How to write custom pool ?](#how-to-write-custom-pool) section, or give me feedback via [issues](https://github.com/mackysoft/XPool/issues) or [pull requests](https://github.com/mackysoft/XPool/pulls).
## Object Pool (Pure C# Object)
`FactoryPool` can be used to pool Pure C# Object.
> Unity Object are not supported, as they behave differently from Pure C# Object in that they can be set to null externally with `Destroy` method.
```cs
// Give the capacity and factory method to the constructor.
var pool = new FactoryPool(8,() => new MyClass());
// Create new instance by factory if pool is empty.
MyClass instance = pool.Rent();
// Return instance to the pool.
pool.Return(instance);
```
## Collection Pool (`T[]`, `List`, `Qeueue`, `Stack`, `HashSet`, `Dictionary`)
An optimized pool is provided for the generic collections provided in .NET Framework.
```cs
// Rent an array from the pool.
// Note that the array length to be rented is the next two powers of minimumLength.
T[] array = ArrayPool.Shared.Rent(minimumLength: 10);
// Return array to the pool.
ArrayPool.Shared.Return(array);
// ListPool, QueuePool, StackPool, HashSetPool, DictionaryPool are also available.
List list = ListPool.Shared.Rent();
Queue queue = QueuePool.Shared.Rent();
Stack stack = StackPool.Shared.Rent();
HashSet hashSet = HashSetPool.Shared.Rent();
Dictionary dictionary = DictionaryPool.Shared.Rent();
```
You can use the TemporaryCollections API that leverages `ArrayPool`.
These collections are a struct and internally use array rented from `ArrayPool`.
Therefore, it is fast and non-allocation.
```cs
// Create a temporary array.
var array = TemporaryArray.Create(10);
// You must release collection when you are done using it.
array.Dispose();
// TemporaryList, TemporaryQueue, TemporaryStack are also available.
TemporaryList list = TemporaryList.Create();
TemporaryQueue queue = TemporaryQueue.Create();
TemporaryStack stack = TemporaryStack.Create();
```
If you want to implement a more customized pool, you can quickly create one by using the provided base classes.
The base class of the pool is in the `ObjectModel` namespace.
- `MackySoft.XPool.ObjectMode.PoolBase`
- `MackySoft.XPool.Unity.ObjectModel.UnityObjectPoolBase`
- `MackySoft.XPool.Unity.ObjectModel.ComponentPoolBase`
```cs
using MackySoft.XPool.ObjectModel; // PoolBase is here.
public class MyPool : PoolBase {
public MyPool () {
}
public MyPool (MyClass original,int capacity) : base(original,capacity) {
}
// Called when Rent is invoked and there are no instances in the pool.
protected override MyClass Factory () {
return new MyClass();
}
// Called when an instance is rented from the pool.
// This is also the case when a new instance is created by the Factory.
protected override void OnRent (MyClass instance) {
}
// Called when an instance is returned to the pool.
protected override void OnReturn (MyClass instance) {
}
// Called when the capacity is exceeded and the instance cannot be returned to the pool,
// or when the instance is released by the ReleaseInstances method.
protected override void OnRelease (MyClass instance) {
}
}
```
### ParticleSystemPool implementation
As an example, `ParticleSystemPool` is implemented using `ComponentPoolBase`.
Its functionality has been optimized for ParticleSystem.
```cs
using System;
using UnityEngine;
using MackySoft.XPool.Unity.ObjectModel; // ComponentPoolBase is here.
[Serializable]
public class ParticleSystemPool : ComponentPoolBase {
[SerializeField]
bool m_PlayOnRent;
public bool PlayOnRent { get => m_PlayOnRent; set => m_PlayOnRent = value; }
public ParticleSystemPool () {
}
public ParticleSystemPool (ParticleSystem original,int capacity) : base(original,capacity) {
}
protected override void OnCreate (ParticleSystem instance) {
var main = instance.main;
main.stopAction = ParticleSystemStopAction.Callback;
var trigger = instance.gameObject.AddComponent();
trigger.Initialize(instance,this);
}
protected override void OnRent (ParticleSystem instance) {
if (m_PlayOnRent) {
instance.Play(true);
}
}
protected override void OnReturn (ParticleSystem instance) {
instance.Stop(true,ParticleSystemStopBehavior.StopEmitting);
}
protected override void OnRelease (ParticleSystem instance) {
UnityEngine.Object.Destroy(instance.gameObject);
}
public class ParticleSystemStoppedTrigger : MonoBehaviour {
ParticleSystem m_ParticleSystem;
IPool m_Pool;
internal void Initialize (ParticleSystem ps,IPool pool) {
m_ParticleSystem = ps;
m_Pool = pool;
}
void OnParticleSystemStopped () {
m_Pool?.Return(m_ParticleSystem);
}
}
}
```
I welcome feature requests and bug reports in [issues](https://github.com/mackysoft/XPool/issues) and [pull requests](https://github.com/mackysoft/XPool/pulls).
If you feel that my works are worthwhile, I would greatly appreciate it if you could sponsor me.
GitHub Sponsors: https://github.com/sponsors/mackysoft
Hiroya Aramaki is a indie game developer in Japan.
- Twitter: [https://twitter.com/makihiro_dev](https://twitter.com/makihiro_dev)
- Blog: [https://mackysoft.net/blog](https://mackysoft.net/blog)
This library is under the MIT License.