Unity3D

Simple Object Pooling for Unity3D

DragonTory 2020. 3. 4. 17:57
반응형

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

public class SimpleObjectPool : MonoBehaviour {

public GameObject Prefab = null;
public int MaxObjectCount = 1;
public bool IsCreatableMore = false;

private Queue Pool= new Queue();

void Awake()
{
    MakePool();
}

public GameObject Pop()
{
    if( Pool.Count == 0 )
    {
        if( IsCreatableMore )
        {
            Debug.log( "It will create one in the object pool" );
            MakePool( Prefab, 1);
        }
        else
        {
            Debug.log( "No more objects available" );
            return null;
        }
    }

    return Pool.Dequeue();
}

public void Push(GameObject item)
{
    item.gameObject.SetActive(false);
    item.transform.SetParent( this.transform, true );

    Pool.Enqueue( item );
}

void MakePool()
{
    MakePool( Prefab, MaxObjectCount);
}

void MakePool( GameObject  prefab, int count )
{
    for( int i = 0; i < count; ++i )
    {
        GameObject go = Instantiate( prefab );

        go.SetActive(false);
        go.transform.SetParent(this.transform, true );

        Pool.Enqueue( go );
    }
}


}

반응형