Search Unity

ArgumentOutOfRangeException: Argument is out of range

Discussion in 'Scripting' started by zigglr, Jul 4, 2018.

  1. zigglr

    zigglr

    Joined:
    Sep 28, 2015
    Posts:
    82
    For some reason the 'removeitems' function is causing the following error:

    ArgumentOutOfRangeException: Argument is out of range. Parameter name: index

    Does anyone know why? I have no idea. Thanks for any help

    Code (CSharp):
    1.  
    2.  
    3. int num = 0;
    4.  
    5.     List<string> questionList = new List<string>() { "q1", "q2", "q3"};
    6.     List<string> choices = new List<string>() { "correct1", "c2", "c3", "c4" };
    7.     List<string> answers = new List<string>() { "correct1", "correct2", "correct3", "correct4" };
    8.  
    9. public void removeitems() {
    10. questionList.RemoveAt(num);
    11.             choices.RemoveAt(num);
    12.             choices.RemoveAt(num + 1);
    13.             choices.RemoveAt(num + 2);
    14.             choices.RemoveAt(num + 3);
    15.             answers.RemoveAt(num);
    16. }
    17.  
     
    Last edited: Jul 4, 2018
  2. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    Well, the exception also gives you the line number it happens on, so that'd help you to pinpoint the exact problem.

    Secondly, keep track of how many objects are left in the choices list while removing items. After you've removed the first item, how many items are left in the choices list? Then think about whether "num + 3" really makes sense after you've already removed the first 3 items.
     
    Last edited: Jul 4, 2018
  3. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    I'd also would try to store your question into an extra object, like question with its answer(s), so you can iterate through it or do whatever you want with it. Besides that, it looks like you want to rather clear the choices choices.Clear(); then remove every single item by itself.

    And, as @BlackPete pointed out, keep track of what you doing. If you remove at 0, your 0 + 3 won't work anymore, as your last index is now 2 (0,1,2)