Changing volume of one AudioSource in an array with a slider in Unity

Viewed 270

I am trying to control the volume of the first audiosource in an array with a slider. The problem is that it's telling me there is no definition for 'volume' in audiosources[0].volume. The script is in an AudioManager from a tutorial from Brackeys: Tutorial.

//Volumeslider
    public void VolumeSlider(float newVolume)
    {
        Component[] audiosources;
        audiosources = GetComponents(typeof(AudioSource));
        audiosources[0].volume = newVolume;

The error: 'Component' does not contain a definition for 'volume' and no accessible extension method 'volume' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS1061)

This is my first question.

1 Answers

Even though you have correctly retrieved all the AudioSource components with GetComponents, since the type of the array is Component[], that means each individual element of the array is of type Component.

Component does not have a definition for volume. Think of something like Animator or MeshFilter. Those are also subclasses of Component, so they could be assigned to elements in your array. What would happen if you tried to access their volume properties?

What you should do instead is, be as specific as possible - that is the whole point of a strongly typed language like C#. You could do this:

var audioSources = GetComponents<AudioSource>();
audioSources[0].volume = newVolume;

The major difference is using the "generic" version of GetComponents (the one with < angle brackets >. The reason is then, you actually get an array, AudioSource[] of the correct type, instead of the basic Component type, which A) doesn't have the field you want, and B) needs to be cast to AudioSource before you can use it how you want.

Other improvements I made: camelCase for variable names, inferred variable type (var, so you only have to change it in one place if you need to use another kind of component later. If you mouse over the var it will tell you that the type is actually AudioSource[]), assignment on the same line as declaration (less clutter.)

Related