Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHoward Huang
7,407 PointsRandom.Range is exclusive for the upper-bound integer value
According to the unity docs: http://docs.unity3d.com/ScriptReference/Random.Range.html
For integers, the Random.Range is inclusive for the min and exclusive for the max, therefore the line of code to choose a random sound from the list of AudioClips:
AudioClip randomSound = soundsClips[Random.Range (0, soundsClips.Count - 1)];
should be just...
AudioClip randomSound = soundsClips[Random.Range (0, soundsClips.Count)];
Is this correct?
2 Answers
Nick Pettit
Treehouse TeacherWow, you're absolutely right! I thought Random.Range always used inclusive numbers, but that's probably because I usually use it with floats. When using integers, the max is indeed exclusive (probably to prevent the exact problem I thought I was solving by subtracting negative 1). I just tested this in the game by using some console debugging, and the last sound in the random sound player script never gets played even after ~1000 runs (or I'm extremely unlucky). When the "-1" is removed, all the sounds in the list are included in the selection.
This will require some time to fix, because it's a video fix. I'm hoping to get that done this week.
Andres Badilla
4,692 PointsThe video seems to be correct now
Mark VonGyer
21,239 PointsMark VonGyer
21,239 PointsI think your way is better Nick - Unity have gone against the standard principles on this one when there really isn't any reason to do so!