Skip to content

Instantly share code, notes, and snippets.

@waitxd
Created June 7, 2019 16:46
Show Gist options
  • Save waitxd/9e34a5d5f2c1b4538352aaef0c069735 to your computer and use it in GitHub Desktop.
Save waitxd/9e34a5d5f2c1b4538352aaef0c069735 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using UnityEngine;
using Zenject;
public class CustomPrefabPool<T> where T : Component
{
public class PrefabForComponentFactory : IFactory<T>
{
private readonly T _prefab;
private readonly IInstantiator _container;
public PrefabForComponentFactory(T prefab, IInstantiator container)
{
_container = container;
_prefab = prefab;
}
public T Create()
{
return _container.InstantiatePrefabForComponent<T>(_prefab);
}
}
private readonly IInstantiator _container;
private MonoMemoryPool<T> _pool;
[Inject]
public CustomPrefabPool(IInstantiator container)
{
_container = container;
}
public T Spawn(T prefab)
{
if (_pool == null)
{
_pool = _container.Instantiate<MonoMemoryPool<T>>(new object[]
{
new MemoryPoolSettings()
{
InitialSize = 1,
ExpandMethod = PoolExpandMethods.OneAtATime,
MaxSize = int.MaxValue
},
new PrefabForComponentFactory(prefab, _container)
});
}
return _pool.Spawn();
}
public void Despawn(T go)
{
_pool.Despawn(go);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment