Need a generic pooling system for shooting game
Hi I am new on Unity as well as C sharp. I wish to do a scrolling game where enemies, packs and bullets spawn randomly. I used a spawn script but I have drastical frame rates losses. I wish to generate a pooling system that can work with the Spawn script I used is that possible? And can I have a brief explanation of how a pooling system works? All the explanations I fell on were vague on their use. Spawn script it works great but creates lags : using UnityEngine; using System.Collections;
public class spawn : MonoBehaviour {
// Use this for initialization
public GameObject[] Prefabs;
public float numEnemies;
public float xLft = 19F;
public float xRgt = 85F;
public float yUp = 3.5F;
public float yDwn = -4.5F;
public float spawnCooldown = 1;
private float timeUntilSpawn = 0;
void Start()
{
//gm = GameObject.FindGameObjectWithTag("GameMaster").GetComponent<GameMaster>();
}
// Update is called once per frame
void Update()
{
timeUntilSpawn -= Time.deltaTime;
if(timeUntilSpawn <= 0)
{
// Do your enemy spawns here
for (int i = 0; i < numEnemies; i++)
{
SpawnEnemy(); //Spawn Fxn called
}
// Reset for next spawn
timeUntilSpawn = spawnCooldown;
}
}
private void SpawnEnemy()
{
//Fxn that Spawns the enemy and determines its position, Trying to make enemy prefab being produced as a child gameObject.
GameObject enemyPrefab = Prefabs[Random.Range(0, Prefabs.Length)];
Vector3 newPos = new Vector3(Random.Range(xLft, xRgt), Random.Range(yUp, yDwn), 0);
GameObject action = Instantiate(enemyPrefab, newPos, Quaternion.identity) as GameObject;
action.transform.parent = transform;
}
}
Answer by Hazzanger · Jul 09, 2016 at 12:33 AM
You're going to want to have multiple states for your pooling objects. For example:
-Active (they are visible and move or whatever)
-Killed or Dying (animation or dying, but can't be pooled yet)
-Dead (invisible and ready to be revived)
All these objects are going to be in an arrayList of GameObjects, or multiple array lists for multiple enemy types. Run through the list and find which enemies are in the "Dead" phase and turn them to "Active"
Your enemies will have to have code to allow for these different states like so
if (active){
//patrol
} else if (dying){
//do the animation and once it's
//done, turn on dead mode
} else if (dead){
//here, you'll make the enemy invisible,
//and when your controller sees it, it will
//put it back in the game
}
and your controller will run through your arraylist of gameobjects like so:
private void spawnEnemy(){
int i = 0;
while (i<enemyArray.length){
if (enemyArray[i].GetComponent(ENEMYSCRIPTNAME).dead){
enemyArray[i].GetComponent(ENEMYSCRIPTNAME).dead = false;
enemyArray[i].GetComponent(ENEMYSCRIPTNAME).active = true;
//If you want to teleport, do that here
i = enemyArray.length;
}
i++;
}
}