PlayerProjectilePool.cs
Description
This script stores a list of GameObjects that become enabled and disabled when the player shoots a weapon set to projectile mode.
Script
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Player
{
public class PlayerProjectilePool : MonoBehaviour
{
public List<GameObject> pooledProjectiles;
[SerializeField] private GameObject objectToPool;
[SerializeField] private int amountToPool;
private GameObject _projParent;
private void Start()
{
_projParent = GameObject.FindGameObjectWithTag("ProjectilePool");
pooledProjectiles = new List<GameObject>();
for (int i = 0; i < amountToPool; i++)
{
var tmp = Instantiate(objectToPool, _projParent.transform);
tmp.SetActive(false);
pooledProjectiles.Add(tmp);
}
}
public GameObject GetPooledProjectile()
{
for (int i = 0; i < amountToPool; i++)
{
if (!pooledProjectiles[i].activeInHierarchy)
return pooledProjectiles[i];
}
return null;
}
}
}
Public Methods
- GetPooledProjectile()
Returns the next non-active projectile in the scene hierarchy.
Variables
- amountToPool
An integer defining the size of the Game Object list - how many projectiles to pool
- objectToPool
The Game Object being pooled i.e. The Projectile Prefab
- pooledProjectiles
List of Game Objects - stores the projectiles to be used by the player
- projParent
The parent game object that will contain all the projectiles to be pooled.
Last modified: 30 April 2024