Audio Random Sounds Out Of Range Error?

Ok I’m trying to get a sound to play from an array. I want my sound to play using an animation even called from a C# script but I keep getting an error message saying:
IndexOutOfRangeException: Array index is out of range.

Here is what I have as my script set up:

//Random Clips
	public AudioClip[] VoiceClips;

public void KITTvoice01()
	{
		
		AudioSource.PlayClipAtPoint(VoiceClips[Random.Range (0, VoiceClips.Length)], Camera.main.transform.position);
	}

How many clips have you assigned to the VoiceClips array in the inspector?

i currently have 4 in the array but want to add more eventually

1 Answer

1

Not Correct, leaving for future readers

Should be VoiceClips.Length - 1, as VoiceClips[VoiceClips.Length] is in fact out of range because it’s 0 indexed :slight_smile:

That's incorrect - Random.Range excludes the Max value, so would only return up to Length-1 anyway.

I tried putting a number value in there and I still get the out of range error?? AudioSource.PlayClipAtPoint(Voices[Random.Range (04, Voices.Length)], Camera.main.transform.position);

Still nothing, does this code even work anymore in the new version of unity?

Does AudioSource.PlayClipAtPoint(voices[3], Camera.main.transform.position); result in an out of range error?

Yes, the script as you see it above results in an out of range error message.