IndexOutofRangeException

Hello, have an index out of range exception, but I don’t know how,

int randomClip=Random.Range(0,clips.Length);
AudioSourcesource=gameObject.AddComponent();
source.clip=clips[randomClip];

thought that since I was using clips.Length where clips is the name of my array, it wouldn’t use a number larger than the size of the array. This is in the awake function, does that matter?

Length is the number of elements in the array, but the index of the array starts at 0, which means it will only go as high as Length-1. Use Length-1 as your upper bound:

int randomClip = Random.Range(0, clips.Length-1);

E.g:

clips[0]
clips[1]
clips[2]
clips[3]

^There are 4 elements in the array, but clips[4] will throw an exception.

How are you defining clips?

I would also suggest you do a debug.log after your int declaration. See what clips.length is and see what randomClip is.

Incorrect. Random.Range as an int is exclusive https://docs.unity3d.com/ScriptReference/Random.Range.html
This means it isn’t going to return the length. -1 will cut off the top value.

Looks like it says inclusive to me. Are we looking at the same version?

EDIT: It’s worth mentioning that I don’t actually know how a float assignment to an int will end up. Does it truncate or round?

It is exclusive. Floats are inclusive. Ints are exclusive.
Random.Range(1f, 5f) can return 5f.
Random.Range(1,5) will not return 5.

Floats are on top, scroll down for the int call.

Oh I see, I was looking at the float one. That explains everything.

I get twice as many debug entries than I expected, but one of them does return that my clip length is 2, and I only have 2 entries which I would assume would be 1.

If this is called in awake on a single object, you should only get the debugs once.

If you have 2 clips in your array, clips.length should be 2
randomClip should either be 0 or 1

Do you have this script in your scene on multiple objects?

Is clips a public variable that you dragged and drop or how are you setting it up?

the array is public and setting it up by typing the size in and dragging and dropping audio files to fill it out.
Strangely, though its on only one object, the debug log upon awake looks like
randomClip = 0
clip.length = 0
IndexoutofRangeException error
randomclip = 1
clip.length = 2

That really looks like it’s on two objects. Is it possible that the object which has it gets duplicated at runtime? Or that a prefab which gets instantiated has it?

Yep, the answer was simple. Had an instance of the script on a child of the main object, which did not need it. Deleting that fixes all problems.