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\$
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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.