Why the program will crash if we store randomly generated variable in the variable index?

Why the program will crash if we store randomly generated variable in the variable index as shown in the lecture? How is storing it directly in the password help to solve this crash?

password = levelPassword[Random.Range(0, levelPassword.Length)];
break;

1 Like

Hello Sarah,

I’m not certain of the exact context, e.g. time from lecture, but…

When you access an element in an array, in this case levelPassword you specify the index of the element in question. You will recall that an array is zero-based, e.g. the first element is index 0. If you try to access an element which is outside of the size of the array, you will receive an error, as an example;

string[] levelPasswords = new string[] { "red", "blue", "green" };

Debug.Log(levelPasswords(3);

In the above, an error is produced because I am trying to access the element with an index of 3, but the elements in our array would have index values of 0, 1 and 2.

In the code example you give you are stating specifically that the random number which is generated has to be between 0 (the first element) and the array length, as such your returned random number should be within the bounds of the array.

I say should because this still isn’t a full proof example. If the array had no elements then you would be asking for a random number between zero and zero, your result would be zero, you’d then be asking for the first element in the array, which wouldn’t exist. However, as we know we have created the password array in this situation it’s kind of overlooked.

There is no reason why that Random.Range statement couldn’t have been on a separate line of code, for example;

int index = Random.Range(0, levelPassword.Length);

password = levelPassword[index];

If you wanted to protect against the issue I described above, you could consider this;

if(levelPassword.Length > 0)
{
    int index = Random.Range(0, levelPassword.Length);

    password = levelPassword[index];
}
else
{
    Debug.LogError("levelPassword array doesn't contain any passwords!);
}

I hope the above helps answer your question, if not, please let me know and I’ll try again, but maybe provide the specific time frame from the video in question to help me. :slight_smile:

Thanks Ben, That helps!

1 Like

hehe, Rob, but you are welcome :wink:

Privacy & Terms