0
\$\begingroup\$

I'm currently having trouble getting my head around how Random.Range() and Array[].Length are working in the script below.

public class SpawnManager : MonoBehaviour
{
    public GameObject[] animalPrefabs;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.S))
        {
            int animalIndex = Random.Range(0, animalPrefabs.Length);
            Instantiate(animalPrefabs[animalIndex], new Vector3(0, 0, 20), animalPrefabs[animalIndex].transform.rotation);
        }
    }
}

Array: Three Elements (0, 1 and 2)

Documentation: Random.Range()'s Minimum and Max are Inclusive

Here, animalIndex is being assigned by Random.Range() a random number between 0 and the animalPrefabs[] array's length, which is 3. According to the documentation (both Visual Studio's and Unity's), both the minimum and maximum Random.Range() numbers are inclusive, which means Random.Range()'s possible outputs would amount to 4 numbers (0, 1, 2 and 3). However only 3 animalPrefabs[] (0, 1 and 2) are defined, as shown in the picture above.

Testing the script, however (printing Random.Range()'s outputs to the console), Random.Range() seems to be generating numbers from 0 to 2 only.

Is the documentation simply wrong? Otherwise, what's going on?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

You are using the public static int Range(int min, int max); overload, which as per the documentation is inclusive for the lower boundary, and exclusive for the upper boundary. The documentation you see in Visual Studio is for the version accepting floating point parameters. The overload accepting integers is documented below the floating point version on Unity's documentation page.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.