Advertisement
lcfr822

GameObjectPooler

Mar 28th, 2020
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.13 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class GameObjectPooler
  6. {
  7.     public int maxPoolSize = 5;
  8.  
  9.     private GameObject poolObject;
  10.     private List<GameObject> pooledObjects;
  11.  
  12.     /// <summary>
  13.     /// Creates a new instance of GameObjectPooler and
  14.     /// Instantiates the maximum number of GameObjects.
  15.     /// </summary>
  16.     /// <param name="t">Original copy of GameObject to pool.</param>
  17.     public GameObjectPooler(GameObject newPooledObject)
  18.     {
  19.         poolObject = newPooledObject;
  20.  
  21.         for (int i = 0; i < maxPoolSize; i++)
  22.         {
  23.             GameObject newObject = Object.Instantiate(poolObject);
  24.             newObject.gameObject.SetActive(false);
  25.             pooledObjects.Add(newObject);
  26.         }
  27.     }
  28.  
  29.     /// <summary>
  30.     /// Retrieves the first inactive pooled GameObject and
  31.     /// returns it.
  32.     /// </summary>
  33.     /// <returns>First inactive pooled GameObject.</returns>
  34.     public GameObject GetPooledObject()
  35.     {
  36.         for (int i = 0; i < pooledObjects.Count; i++)
  37.         {
  38.             if (!pooledObjects[i].gameObject.activeInHierarchy)
  39.             {
  40.                 return pooledObjects[i];
  41.             }
  42.         }
  43.  
  44.         return null;
  45.     }
  46.  
  47.     /// <summary>
  48.     /// Returns an active pooled GameObject to inactive state.
  49.     /// </summary>
  50.     /// <param name="toPoolObject">Pooled GameObject to be returned.</param>
  51.     public void ReturnPooledObject(GameObject toPoolObject)
  52.     {
  53.         toPoolObject.gameObject.SetActive(false);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement