Ed

Ed

  • NA
  • 3
  • 0

Disposing of an object within another object

Dec 15 2008 4:00 PM
Hello,

I am trying to create a basic war game. I have two classes, called Army, and Unit.

Army contains an array of 10 Units:

public class Army
{
public Unit[] units;

public Army()
{
units = new Unit[10];
}
}

When my program runs, an Army class is created, which creates an array of 10 Units. Each unit has a member called "health", and each unit performs a variety of tasks when the method Process() is called, which may decrease the value of "health". Every now and then, a unit's health may be reduced to zero, in which case, I want to destroy this unit, and remove it from the array in the parent instance of Army.
Here is the Unit class:

public class Unit
{
int health;

public Unit()
{
health = 100;
}

public void Process()
{
//
// a few tasks are performed, which may decrease the value of health
//
if (health <= 0)
{
Die();
}
}

private void Die()
{
// I need to put some code in here!
}
}


When Die() is called, I want to basically remove this instance of Unit from memory, and remove it from thhe array in the Army class, which it belongs to.

I tried doing this by simply setting this instant of the unit as null, ie:

private void Die()
{
this = null;
}

This appears to set this instance of the unit to null, BUT it does not any of the Units in the Army array to null. Each Unit in Army.units remains untouched, none of them are null when I debug.

But I want to be able to delete this instance of Unit from this array.

How can I do this???

Thank you so much :)

Ed.

Answers (1)