Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How do I make an if statement for when list is empty

Discussion in 'Scripting' started by okaybj, May 17, 2020.

  1. okaybj

    okaybj

    Joined:
    Nov 15, 2018
    Posts:
    33
    I am trying to ask a series of random questions to the player until all are asked then end the game. I get this error when the randomly generated list is empty. I'm wondering how to make an if statement for once the list is empty. I've tried all the different variations of if list = 0 or if i or if list.Count but I have no idea what I'm doing.

    Code (CSharp):
    1.   List<int> list = new List<int>();   //  Declare list
    2.   for (int n = 0; n < 10; n++)    //  Populate list
    3.   {
    4.       list.Add(n);
    5.   }
    6.   int index = Random.Range(0, list.Count - 1);    //  Pick random element from the list
    7.   int i = list[index];    //  i = the number that was randomly picked
    8.   list.RemoveAt(index);   //  Remove chosen element
    9.   //  Loop lines 10-13 as many times as needed
     
  2. ErwanTLG

    ErwanTLG

    Joined:
    Apr 15, 2018
    Posts:
    3
    You can check if the list is empty with
    Code (CSharp):
    1. if (list.Count == 0)
    This will avoid getting an error because the random index was out of range
     
  3. okaybj

    okaybj

    Joined:
    Nov 15, 2018
    Posts:
    33
    Thank you for your help. I'm using this

    Code (CSharp):
    1. if (list.Count == 0)
    2.             {
    3.                 Debug.Log("you win!");
    4.             }
    and I get this error

    ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index
     
  4. okaybj

    okaybj

    Joined:
    Nov 15, 2018
    Posts:
    33
    Actually I am using
    Code (CSharp):
    1. for (int n = 1; n < 6; n++)    //  Populate list
    2.             {
    3.             list.Add(n);
    4.             }
    so the n isn't = 0

    im fiddling with it now
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Please copy and paste the entire error message. It will include a line number in your code. It's really hard to tell what the problem is without having that line number.