Detinator10
Detinator10

Reputation: 123

How to mark instance for deletion in XNA/Monogame

In my tower defense game I am making when my enemies die, well I want them to die right? So, I need to delete them. I am coming over from C++ where you can just delete instances of a class with delete MyInstance;, but that doesn't work in C#. I know that there is a garbage collector in C# that deletes things for you, but, how do you mark an instance for deletion? Thank YOU!!!

Upvotes: 1

Views: 1555

Answers (2)

RomSteady
RomSteady

Reputation: 398

My recommendation would be to not delete them. While you have a garbage collector to help out, not using it can often be your best choice from a performance point of view.

Think of the maximum number of enemies you could potentially have.

Create a circular buffer of Enemy objects: essentially an array of Enemy objects and a last pointer.

Add an "IsActive" flag to each Enemy.

When you want to create a new enemy, walk forward through the circular buffer from the last pointer until you find an Enemy that has its IsActive flag set to false. Set the last pointer to that enemy, make that enemy into the type that you care about, and set its IsActive flag to true.

When the enemy dies, set its IsActive flag to false.

In your Update and Draw loops, you just iterate through the buffer and either act on or draw each Enemy that has IsActive set to true.

Upvotes: 4

Mariano
Mariano

Reputation: 1073

You can explicitly set an object to null, that will mark it for garbage collection.

Enemy e = new Enemy();

// do stuff with enemy

// Set to null
e = null;

Upvotes: 3

Related Questions