Play AudioClip index of ouf range.

Been racking my brains for a few days on this now but i’m stumped and i’m guessing its an easy fix i just can’t see.

When i run the game I get the error “indexoutofrangeexception” Which i assume is telling me the array is somehow not working.
Annoying this is - I copied this code from another script which actually worked so I have no idea why it’s messing up now :frowning:

Checked the answers and tried a few different ways of coding it but no luck and I think I’ve tangled myself up.

Situation - car hits enemy, enemy dies, spawns empty GO which plays the sound effect.
Sound effect is meant to be random from 4 sound effects - here is the code.
And yes I have set the array in the inspector to ‘4’ and then added 4 different audio clips and there is also an audio source on the object.

var splatSounds : AudioClip[];

function Start () {
	playSound();
}

function playSound()
{
	//audio.clip = splatSounds[0];
	//audio.Play();
	audio.PlayOneShot(splatSounds[Random.Range(0,splatSounds.Length)]);	
}

The commented out bit is an alternative method I tried which didn’t work but I included it in case that method was closer to working!

2 Answers

2

Index is 0 based and “splatSounds.Length” returns count, So try:

audio.PlayOneShot (splatSounds[Random.Range(0,splatSounds.Length-1)]);

Thanks for the response. Before applying your code I went back and double checked - turned down the ambient sounds - and noticed that the sounds WERE playing as expected but obviously the error was still there. Then I applied your code, and its exactly the same lol! Sounds play but error is still moaning at me, grr. Any further ideas? I appreciate the response by the way.

You were right - the problem was occurring because I had added the script to another object without realising and hadn't filled the array in on the inspector. It works fine now, thank you both for your help :)

strange, seems like it should be OK. But just take it one step at a time and see when the errors go away. So try Random.Range(0, 4), then (0, 3), etc. and use Debug.Log to check what values are coming through. Or go back even further and try hard-coding the numbers: splatSounds[0], [1], [2], [3], [4]…where do you start getting the error? Might give a hint.