level1Passwords.Length Counting Curiosity

This isn’t anything critical, I’m just curious:
if the length of the level1Passwords array is 6 (there are 6 items in the array), wouldn’t the random generator read
Random.Range(0, level1Passwords.Length)
as
Random.Range(0, 6)
?

How does it automatically know to go 0-5, not 0-6? Am I misunderstanding .Length, or is there some funny business going on under the hood?

1 Like

This is an interesting one. I added the following PlayMode test to Hacker.cs to show that the code works as is:

[UnityTest]
    public IEnumerator TestRandomRangeArrayNotOutOfBounds() {
        int numIterations = 1000;
        Debug.Log("Level 1 Passwords Length:" + level1Passwords.Length);
        Debug.Log("Test runs: " + numIterations);
        int[] results = {0, 0, 0, 0, 0, 0, 0};
        for (int i = 0; i < numIterations; i++) {
            int randResult = Random.Range(0, level1Passwords.Length);
            Assert.AreNotEqual(randResult, level1Passwords.Length);
            results[randResult]++;
        }
        Debug.Log("Results: " + String.Join(",", results.Select(x => x.ToString()).ToArray()));
        yield return null;
    }

Which returns as follows in the TestRunner:

TestRandomRangeArrayNotOutOfBounds (0.045s)

Level 1 Passwords Length:6
Test runs: 1000
Results: 179,168,178,168,139,168,0

So you can see that 6 is never returned from Random.Range(0, level1Passwords.Length) even though the Length is 6.

Now I thought this was curious, as the API docs state that the min and max of Random.Range are inclusive, so the result should be 0…6.

Returns a random float number between and min [inclusive] and max [inclusive] (Read Only).

HOWEVER :slight_smile:

If you scroll further down the page, you can see that Random.Range is overloaded for ints, and when you use ints instead of floats, the max is exclusive:

Returns a random integer number between min [inclusive] and max [exclusive] (Read Only).

Mystery solved :slight_smile:

3 Likes

Ahhhh, I see. Good detective work. Thank you!

Privacy & Terms