does destroying a game object remove it from any lists it was in?

This is a really nooby question and I apologise. What I have is a colony which contains many buildings, they will probably be stored in a list, if I was to press remove building on any building, i’d need to destroy it, so i will have a remove method in the building script that will essentially destroy the building it is attached too…

What i’m wondering is when I do this what will happen to the colonies list of buildings…
Will it automatically remove the object from the list and clean itself up, or will I get errors where it is trying to find object at given index that doesn’t exist any more?

It’s easy to fix it by just using list.remove before doing gameobject.destroy I imagine, but I just want to know for the sake of furthering my understanding for future what I should do.

Thanks guys.

no

that’s why you get NRE

if some else scripts want to access that GO you’ll get NRE

and as you said yes you should do:

ListName.remove(ThatGameObject);
Destroy(ThatGameObject);

or as I and many do - I pool it

ListName.remove(ThatGameObject);
ThatGameObject.SetActive(false);

for deactivating you can do it before or after it’ll be same but not for destroy.

happy coding

You have the right idea… You will need to remove the item from the list. That index will be null if you try to access it after destroying the object its referencing.