Search Unity

Check if Array element has value or not

Discussion in 'Scripting' started by DarkEcho, Aug 28, 2015.

  1. DarkEcho

    DarkEcho

    Joined:
    Jul 7, 2014
    Posts:
    233
    How do I check if an Array element has a value assigned?

    This is my current code...
    Code (CSharp):
    1. for (int i = 0; i <= monstersList.Length; i++)
    2.             {
    3.                 Debug.Write("in loop");
    4.                 if (monstersList[i] != null)
    5.                 {
    6.                     //do stuff with free element
    7.                 }
    8.             }
    ...and this is my solution...
    Code (CSharp):
    1.  if (monstersList[i] != null)
    ...but it keeps throwing out the 'out of range error' so clearly my solution is wrong.
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    It's not wrong, the error states that you're trying to address an invalid index, which happens due to your condition ' <= '. It should only be ' < '.