- Home /
Cleaning Up Classes In Lists
I've had a concern for a while, and from searching around I haven't been able to find a definite answer. When making a list of any given class, by simply removing that class from the list, within Unity, does that inherently remove the class from memory, or are there further steps that need to be taken to make sure this happens? Normally such a thing would lead to a memory leak, but I haven't yet had this problem with Unity (from what I can tell) but it makes me a little cautious when I don't know.
Answer by fafase · Aug 14, 2013 at 11:02 AM
Removing an item from a list only remove the reference to the item contained in the list. A list does not hold the object but just a reference to it.
As a result, when doing:
list.RemoveAt(index);
the object is still in memory and could still be retrieved with GameObject.Find("Name").
This below will remove the object on collision:
void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag == "Projectile"){
projectileList.Remove(col.gameObject);
Destroy(col.gameObject);
}
}
That considers you are storing your projectile in a list right after you instantiate them. This will remove from the list and destroy the object. Later on garbage collector will free the memory when needed.
I don't specifically mean game objects that are in the heirarchy, I mean a list of classes that is held purely as information. Not game objects. Is the rule the same?
oh you mean removing a script from an object. That cancels the creation of the instance of the object yes.