The problem is that GetComponents returns an array of Components, and while AudioSource is a kind of Component, the language doesn’t regard AudioSource[ ] as being a kind of Component[ ], so it won’t allow you to assign the latter to the former.
I tried using the ‘as’ operator, as suggested by rom, but in Javascript it merely allows the code to compile and appears to silently fail to do the conversion (by returning null) at runtime.
Here’s one way that does work:
var sounds : Component[];
function Start()
{
sounds = GetComponentsInChildren(AudioSource);
(sounds[0] as AudioSource).volume = 0.5;
for(var sound : AudioSource in sounds)
{
sound.volume = 0.5;
}
}
Typing the array as Component[ ] allows the assignment to work, but if you’re using static typing (#pragma strict or Unity iPhone) you’d want to make sure you specify the type when you access members of the array. I’m not sure if all this runtime casting has significant overhead.
A slightly messier way of getting the right type of array upfront would be to do this:
var sounds : AudioSource[];
function Start()
{
sounds = Array(GetComponentsInChildren(AudioSource)).ToBuiltin(AudioSource);
sounds[0].volume = 0.5;
for(var sound in sounds)
{
sound.volume = 0.5;
}
}
That way you have to pay a bit more to convert the array of Components to an array of AudioSources, but after that there will be no extra type verification overhead.
Again, I’m not sure if the overhead of the first example is actually significant. You might want to do some tests to see if it’s worth your while doing it the other way.
Incidentally, I was aware of this situation in C#, but I didn’t know that Javascript was also affected. If anyone else has a better solution, I’d be keen to hear it!
[EDIT: made the conversion into a one liner in the second example!]