Adding and Removing Objects from Lists

Hi all,
I have some trouble implementing something like Containers currently that can store so called “Garage Objects” in my game. In the prefab of the Container I already add one “GarageObject” to the containedGarageObjects List.
I use a List currently and add and delete the corresponding GarageObjects accordingly. But it seems like Lists in C# work quite differently than in Java. List.Count always returns the entire Lists size and not only the amount of elements that are not null which makes accessing the last element of the List quite tedious. I tried using List.TrimExcess() so the List is always at the correct size but that also does not work.
What is the best/most elegant way to go about this in Unity?

In Unity you can always prune a list of ALL Destroyed or null UnityEngine.Objects with:

myListOfGameObjects.RemoveAll( x => !x);

Which is schmincy-schmancy way of saying “remove everything that tests false,” which in tern makes use of the UnityEngine.Objects boolean overload.

That won’t work for lists of things that don’t implement such an overload.

Otherwise a null is just as valid as a GameObject as far as a List() is concerned.

Any reference type can be null, and hence can be stored in a List()

Also remember that Destroy() doesn’t actually happen until end of frame. This means if you Destroy() something and immediately ask “Is this destroyed?” the answer will be “Nope.”

1 Like

BTW if you’re making a stack of these things and you want to always add/remove from the top of the stack, there is actually precisely such a thing for you, the Stack<T>() type.

Thanks a lot for the reply! I thought about using a Stack but found it might restrict me later if I want to have Containers where I not only want to remove the last object but also maybe something from the middle or something like that.
I will try out your other suggestion and report back.

If you wanna remove from anywhere, definitely use a List()

Remember that you can call .Remove() to remove a particular item, but be careful: if you have TWO of the same item in the list and you say .Remove(), it only removes the FIRST one it finds. This is all covered in the docs for List()

Otherwise thare is also .RemoveAt() which accepts an integer saying “remove this element regardless of what it is.” It is subject to all the same indexing rules: you MUST specify an existing item.

1 Like

Can you show us an example of how your list is expected to work?
Because you got me confused here: List.size in Java works exactly the same as List.Count in C#.