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
                }
    }
2
  • Do you absolutely need to use an array? If not, why not using a List of Enemy instead? :) Commented Nov 29, 2015 at 1: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 Commented Nov 29, 2015 at 1:36

1 Answer 1

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.