KEMBAR78
Gameobjectpool | PDF
0% found this document useful (0 votes)
31 views1 page

Gameobjectpool

This document describes a GameObjectPool class that is used to spawn and return prefab game objects. The class spawns prefab game objects from a queue if available, or instantiates a new one if the queue is empty. It also returns game objects to the queue to be reused later.

Uploaded by

api-544307512
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views1 page

Gameobjectpool

This document describes a GameObjectPool class that is used to spawn and return prefab game objects. The class spawns prefab game objects from a queue if available, or instantiates a new one if the queue is empty. It also returns game objects to the queue to be reused later.

Uploaded by

api-544307512
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

using System.

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

//this class is semi-generic, because it spawns a prefab, which is ALWAYS a


gameobject
public abstract class GameObjectPool<T> : Singleton<GameObjectPool<T>>
where T : Component
{
[SerializeField] protected GameObject prefab;
private Queue<GameObject> objects = new Queue<GameObject>();

new private void Awake()


{
base.Awake();
}

//returns a GameObject from pool or creates one if none is left


public GameObject GetObject(Vector3 spawnPos)
{
GameObject obj;
if (objects.Count == 0)
{
obj = (GameObject)Instantiate(prefab, spawnPos, Quaternion.identity);
}
else
{
obj = objects.Dequeue();
obj.transform.position = spawnPos;
}
obj.gameObject.SetActive(true);

return obj;
}

//puts a gameObject back to the pool


public void ReturnToPool(GameObject obj)
{
obj.gameObject.SetActive(false);
objects.Enqueue(obj);
}
}

You might also like