- Home /
Creating an "Importance Manager" to destroy older GameObjects from a list to make way for new GameObjects.
Hey guys, I am a huge fan of destruction. Because of that, at any given time I can have a lot of GameObjects that use gravity for debris and whatnot. I was hoping someone can help me with the code I'm making that will only allow a set number of GameObjects be active before it starts destroying them so that new ones can appear. I say destroy and not deactivate because I will never need to see them again.
For starters I have my ImportanceManager script.
public static List<GameObject> Expendable = new List<GameObject>();
void Update()
{
if (Expendable.Count >= 100)
{
Destroy(Expendable[0]);
}
}
Next up is the script I put on the objects that use gravity.
public void OnEnable()
{
ImportanceManager.Expendable.Add(gameObject);
}
The problem is that the new GameObjects that are SetActive do not re-write over the GameObjects on the list. So what my script does is it delete 1 GameObject once it hits over 100, and theeeen... Nothing. How would I go about letting the newer activated GameObjects start from the top of the list so the oldest ones get destroyed first? Thanks!
Answer by rodimus_strom · Apr 25, 2021 at 07:42 AM
Issue because you are not removing the element from the list. So after the first time it executes Expendable[0] is null, so you have to call Expendable.RemoveAt(0); this will remove the 0th element.
Or you can use a different Data Structure maybe queue instead of list. Here a small example this will save the update too because you just need to check when you add element to queue.
public class ImportanceManager : MonoBehaviour{
public static Queue<GameObject> Expendable = new Queue<GameObject>();
public static void AddToQueue(GameObject go) {
Expendable.Enqueue(go);
if(Expendable.Count >= 100) {
var obj = Expendable.Dequeue();
Destroy(obj);
}
}
}