Hello,
I did the Object Pooling - Unity Learn tutorial to improve the performance of my tower defense game.
It worked well but my game is a little different from the course game, there are several objects that shoot(the turrests), and these objects can be created or sold.
And when I sell one of the towers there are several inactive objects in the hierarchy.
This is the turret script (bullets part)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Turret : MonoBehaviour
{
// Object Pooling
[SerializeField] private int pooledAmount = 0;
List<GameObject> bulletsList;
void Start()
{
// Object Pooling
bulletsList = new List<GameObject>();
for (int i = 0; i < pooledAmount; i++)
{
GameObject obj = (GameObject)Instantiate(bulletPrefab);
obj.SetActive(false);
bulletsList.Add(obj);
}
}
void Shoot()
{
for (int i = 0; i < bulletsList.Count; i++)
{
if(!bulletsList[i].activeInHierarchy)
{
bulletsList[i].transform.position = firePoint.transform.position;
bulletsList[i].transform.rotation = firePoint.transform.rotation;
bulletsList[i].SetActive(true);
if (bulletsList[i] != null)
{
Bullet bullet = bulletsList[i].GetComponent<Bullet>();
bullet.Seek(target);
}
break;
}
}
}
}
}
This is the bullet script (object poolinh part)
using System.Collections;
using UnityEngine;
public class Bullet : MonoBehaviour
{
void HitTarget()
{
GameObject effectIns = (GameObject)Instantiate(impactEffect, transform.position, transform.rotation);
Destroy(effectIns, 1f);
if (explosionRadius > 0)
{
Explode();
}
else
{
Damage(target);
}
gameObject.SetActive(false);
}
}
This is NodeScript (part of the sale of the turrets)
using UnityEngine;
using UnityEngine.EventSystems;
public class Node : MonoBehaviour
{
public void SellTurret()
{
//GameObject effect = (GameObject)Instantiate(buildManager.sellEffect, GetBuildPosition(), Quaternion.identity);
//Destroy(effect, 2f);
Destroy(turret);
}
}
This are SS from my unity screen with 5 turrets created. There you can see the number of inactive objects referring to the bullets of each turret, and everything is ok. It works fine if I donât sell any turrets.
Now if I sell these turrets and create other turrets, the inactive objects of the sold turrets (destroyed) will remain there, the objects of the new turrets are also there. This can cause many objects at the end of the game, reducing game performance.
My question is: Is there a way to remove these inactive objects from these sold turrets that are in the Hierarchy?