0

I don't know if what I am trying to do is possible in C# and I couldn't find an answer online. I have 4 enemy objects. One of them dies. I want that enemy to be removed from the array. If the enemy is in the middle of the array, I want the next enemy to take its spot so that the array does not have empty spots in the middle. Here is the code (where I wrote "//remove here" is where I want the object to be removed):

    public static int numberOfEnemies = random.Next(1, 4);
    // create 1-4 enemies
    public static Enemy[] enemyNumber = new Enemy[numberOfEnemies]; 

   // initialize enemies
   int h = 0;
         do
         {
               enemyNumber[h] = new Enemy(playerLevel);
               h++;
               System.Threading.Thread.Sleep(25);
         } while (h != numberOfEnemies);

    // code where the fight happens i did not include
    // enemy dies
    if (enemyNumber[0].Ehealth <= 0){
                {
                    Console.WriteLine("Enemy {0} is dead!", eName);
                    // remove here
                }
    }
J.J.
  • 1,128
  • 2
  • 23
  • 62
soso
  • 311
  • 1
  • 4
  • 13
  • Do you absolutely need to use an array? If not, why not using a List of Enemy instead? :) – Kzryzstof Nov 29 '15 at 01:20
  • Use List<> instead of array. It has a method `Remove(YourClass object)` that simply removes your object from a list. You could also use `RemoveAt(int index)` if you know an index of your object etc. ([here's some example](http://stackoverflow.com/questions/10018957/c-sharp-remove-item-from-list) – Celdor Nov 29 '15 at 01:36

1 Answers1

1

You're better off using a list as someone mentioned. This will allow you to remove objects and not worry about empty space (it will be filled by the next object) If not, you will need something like this each time something is removed from the array (Assuming Enemy is not a struct)

enemyNumber = enemyNumber.Where(enem => enem != null).ToArray();

Also rename enemyNumber because it's an array of enemies, not an a single number :)

William
  • 1,837
  • 2
  • 22
  • 36
  • It is not a full answer. Using this method on a container with custom objects also requires something else to define in order for predicates to work. – Celdor Nov 29 '15 at 01:41