0

I'm trying to creat a delete character in a text game, this code would use a way were the player use his Character ID to delete the character, the ID is the position +1 in the list, but for now i can't delete the character because it's says that is out of bounds.

public static void DeletarJogador()
{
    int ID;
    Console.WriteLine("Characters resting at barracks: \n");
    foreach(Player p in Listas.jogadores)
    {
        Console.WriteLine($">Name: {p.NomePlayer}           ID: {p.IDPlayer}");
        Console.WriteLine();
    }

    while(true)
    {
        Console.Write("Choose a character to delete, by ID: ");
        ID = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(Listas.jogadores.Count);
        for(int i = 0 ; i <= Listas.jogadores.Count; i++)
        {
            Console.WriteLine(Listas.jogadores.Count);
            if(ID == Listas.jogadores[i].IDPlayer)
            {
                Listas.jogadores.RemoveAt(ID);
            }
        }
        break;
    }
}
maccettura
  • 10,514
  • 3
  • 28
  • 35
  • Had you stepped through the code in a debugger (one of the primary techniques described in the marked duplicate), you would have seen exactly the problem: that the value you passed to the `RemoveAt()` method is not without the range of valid values, and in fact is not the value you intended to pass. NOTE: in addition to that issue, your `for` loop will need some work, as you either need to break out of the loop after removing an item or adjust the loop index to account for the removed item, and the final `break` means the `while (true)` is completely pointless. – Peter Duniho Mar 15 '20 at 00:58
  • Thanks for the help, for some reason Repl.it didn't show me that, and also thanks for telling me about the break on the end. – galbe-droid Mar 15 '20 at 01:01

1 Answers1

1
Listas.jogadores.RemoveAt(ID);

Should be:

Listas.jogadores.RemoveAt(i);
rfmodulator
  • 3,638
  • 3
  • 18
  • 22