Creating a volume slider

Okay, I’ve been Googling info on how to create a volume slider for a few days now, and can’t find anything recent that I actually understand. Here’s what I attempted to do.

I’ve got a bunch of objects that play an audio clip when they are interacted with by a user or other objects. The audio clip is attached to those objects, and those objects are all tagged with the tag “Crystal”.

I created a slider, and the OnValueChanged() is connected to my GameController.AudioSlider(), which is as follows:

publicvoidAudioSlider(floatvolume)
{
foreach (GameObject crystal in GameObject.FindGameObjectsWithTag(“Crystal”)) {
crystal.GetComponent().volume = volume/100;
}
}

I get the error “The referenced script on this behavior is missing”.

So what am I doing wrong?

Looks like one or more of your Crystal GameObject’s don’t have an AudioSource component.

Try to narrow it down by checking for null and logging the name:

AudioSource source = crystal.GetComponent<AudioSource>();

if(source == null)
     Debug.Log("Missing AudioSource on " + crystal.name " + " GameObject");

That doesn’t seem to be the problem. All the Crystal objects are generated from a prefab, which is where the audio source is located. To be sure, I checked each individual crystal to verify…

You should be able to click on the error and have the object highlighted in the hierarchy.

This error doesn’t mean that GetComponent can’t find anything, that would give a null reference error.

This error means that one of the GameObjects in your scene has a script on it that has been deleted or renamed, and the editor can’t find the script.

For a global volume slider you can always adjust the audio listener volume instead of the source volume.

Ok, so I tried changing my script to the following to use the AudioListener volume instead.

public void AudioSlider(float volume)
{

Camera.main.GetComponent().volume = volume / 100;

}

And now get the error:

Assets/Scripts/GameController.cs(237,59): error CS0176: Static member `UnityEngine.AudioListener.volume’ cannot be accessed with an instance reference, qualify it with a type name instead

AudioListener.volume is static. So no need to use GetComponent.

AudioListener.volume = volume / 100;

Thank you! This works perfectly now.