ObjectPool 對象池的代碼

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


public class ObjectPool : MonoBehaviour
{
    public GameObject prefab;
    private Stack<GameObject> inactiveInstances = new Stack<GameObject>();


    public GameObject GetObject(Transform parent)
    {
        GameObject spawnedGameObject;


        if (inactiveInstances.Count > 0)
        {
            spawnedGameObject = inactiveInstances.Pop();
        }
        else
        {
            spawnedGameObject = GameObject.Instantiate(prefab);


            PooledObject pooledObject = spawnedGameObject.AddComponent<PooledObject>();
            pooledObject.pool = this;
        }


        spawnedGameObject.transform.SetParent(parent, false);
        spawnedGameObject.transform.SetAsLastSibling();
        spawnedGameObject.SetActive(true);


        return spawnedGameObject;
    }


    // Return an instance of the prefab to the pool
    public void ReturnObject(GameObject toReturn)
    {
        PooledObject pooledObject = toReturn.GetComponent<PooledObject>();


        // if the instance came from this pool, return it to the pool
        if (pooledObject != null && pooledObject.pool == this)
        {
            // make the instance a child of this and disable it
            toReturn.transform.SetParent(this.transform, false);
            toReturn.transform.SetAsLastSibling();
            toReturn.SetActive(false);


            // add the instance to the collection of inactive instances
            inactiveInstances.Push(toReturn);
        }
        // otherwise, just destroy it
        else
        {
            Debug.LogWarning(toReturn.name + " was returned to a pool it wasn't spawned from! Destroying.");
            Destroy(toReturn);
        }
    }
}


// a component that simply identifies the pool that a GameObject came from
public class PooledObject : MonoBehaviour
{
    public ObjectPool pool;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章