Game Development Community

Safe way to delete an object in a List?

by Matthew Shapiro · in Torque X 2D · 04/03/2008 (7:31 pm) · 2 replies

So I'm writing my projectile code, and I have a class that is keeping a list of projectiles that exist, and each tick it iterates through the list to make sure each object doesn't live past its lifetime. If it does last longer than its lifetime I want to delete the T2DSceneObject and remove it from the list.

My List is:
protected struct missileObjectData
        {
            public float timeAlive;
            public T2DSceneObject missileObject;
        }

        protected List<missileObjectData> _missiles;

Now my question is how to safely delete the object. I know the traditional way to delete an object is to set the MarkForDelete property to true. However, not knowing the particulars of how C# handles garbage collection/scope I am afraid that if I mark it for deletion then in the next line delete the structure from the list that T2DSceneObject could be deleted without proper unregistration.

Are my concerns founded or should I not have anything to worry about?

#1
04/03/2008 (11:46 pm)
I don't think you have anything to worry about. Marking the object for delete and then immediately removing the List - everything will shutdown in order. To help avoid unexpected garbage collection, how about caching a fixed number of missiles and adding another property, like enabled/visible/etc, so you can re-use them - rather than create & destroy a bunch of objects. Or even clone the missile from a template with object pooling enabled.

John K.
#2
04/04/2008 (5:09 am)
That's what I thought.

I'm already cloning a template with object pooling. Though caching them might not be a bad idea.

Thanks.