- Home /
Question about arrays.
Hi, I've always had this doubt and I thought I should clarify it for good since it's quite important, and I see people that either do one way or the other, which confuses me even more. When I do something like, for example, random spawning, I usually first create an int to randomize what will be the index of the spawn, the thing is, should it be:
int i = Random.Range(0,array.Lenght - 1)
or should it be
int i = Random.Range(0,array.Lenght)
I hope I finally understand which one is correct, I think the first one is correct, but I'm not sure.
It depends, I'would use the second one:
int i = Random.Range(0, array.Length);
just because Unitys Random.Range havent returned array.Length for me. But tobe precise you should use array.Length - 1 since index of last item in array is Length - 1.
No, you don't use Length-1. See zharik's answer below; the maximum value is never returned when dealing with integers.
Answer by zharik86 · Jul 27, 2014 at 08:01 PM
Function Random.Range(int min, int max) returns a random integer number between min [inclusive] and max [exclusive]. Generally in Unity help everything is written. For example, you have int array, then:
int count = 9;
int[] myarr = new int[count];//you create array on 9 elements with index from 0 to 8
int num = Random.Range(0, myarr.Lenght); //in numbers Random.Range(0, 9), but result from 0 to 8
I hope it will help you.
Oh I see, so in floats everything is inclusive, and in ints last int is exclusive? I prolly should go through all my game's code and search for those flaws then ;), thanks a lot for clarifying this