Game Object Pool system.

Hi.
I had made a object pool system.
GameObject.Instantiate function is too heavy to call when runtime.
You can use this script when you want to make some game objects with no delay.
I hope this help you. Thank you.

This source code is ‘Free license’.

using System.Collections;
using System.Collections.Generic;

/*
 * Usage
 * 
 * CGameObjectPool<GameObject> monster_pool;
 * ...
 * 
 * // Create monsters.
 * this.monster_pool = new CGameObjectPool<GameObject>(5, () => 
	{ 
		GameObject obj = new GameObject("monster");
		return obj;
	});
	
	
	...
	
	// Get from pool
	GameObject obj = this.monster_pool.pop();
	
	...
	
	// Return to pool
	this.monster_pool.push(obj);
 * */
public class CGameObjectPool<T> where T : class
{
	// Instance count to create.
	short count;
	
	public delegate T Func();
	Func create_fn;
	
	// Instances.
	Stack<T> objects;

	// Construct
	public CGameObjectPool(short count, Func fn)
	{
		this.count = count;
		this.create_fn = fn;

		this.objects = new Stack<T>(this.count);
		allocate();
	}
	
	void allocate()
	{
		for (int i=0; i<this.count; ++i)
		{
			this.objects.Push(this.create_fn());
		}
	}
	
	public T pop()
	{
		if (this.objects.Count <= 0)
		{
			allocate();
		}

		return this.objects.Pop();
	}
	
	public void push(T obj)
	{
		this.objects.Push(obj);
	}
}

1085510–40670–$gameobjectpool.unitypackage (4.35 KB)

Not to knock you giving to the community, but i think your implementation and naming conventions are rather confusing.
IE: This isn’t a GameObject pool, its an object stack as this can be used with anything. Since its named CGameObjectPool, i’d almost expect it to interface with unity and how gameobjects are controlled with prefabs via GameObject.Instantiate(), and whether or not they are active.
Finally, your only storing them in a stack with no implementation on ensuring the objects are hidden or reusable. I’d rather just use the Stack myself since this is just a wrapper for it. This kind of breaks the pattern of making an object pool in the first place.

I hope you don’t take this as an attack but rather a point of constructive criticism

I concur