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.

You can use an ArrayList instead it has a Remove method

Or just use a list :)

But if the unit need to notify the army that it has died (a little strange in real-life, but not so bad in computers), the unit will need to know which army to notify.

The other option might be for all operations which might 'kill' a unit to come through the army so the army could catch an 'I died' return code to de-list the associated unit.

Thats why classes are great - you could assign a list of units to an army, the list could if using the right class structure hold tanks, troups etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.