Is there a way to make all audio clips in Unity the same volume? The only way I could find is to change the volume of the AudioSource directly from the code, but is there another way?
CodePudding user response:
You're probably looking for the Audio Mixer API. It allows you to assign each audio source to a different "Audio Mixer Group", which you can use to change parameters (volume, in your case) for all audio sources in said group.
Create a new Audio Mixer asset.
Right Click > Create > Audio Mixer
.Open the Audio Mixer window by double-clicking on the newly created asset.
Create new group(s) by hitting the to the right of "Groups" (on the left panel). Having separate "Music" and "Sound Effects" audio levels is achieved by making a "Music" and "Sound Efffect" Audio Mixer Group.
Click on the new group, right click the "Volume" text in the inspector, and click "expose ... to script". This will allow you to change the volume parameter via code.
Back in the Audio Mixer window, expand the "Exposed Parameters" dropdown in the top right.
Rename the parameter from "MyExposedParameter" to something reasonable, like "MusicVolume" or "SfxVolume" (by double-clicking).
In code, when you want to change the audio levels, make a variable referencing the initial AudioMixer asset. You can then use
mixer.SetFloat(parameter, value)
. For example:
using UnityEngine;
using UnityEngine.Audio; //required import for AudioMixer
public class AudioChanger : MonoBehaviour {
[SerializeField] AudioMixer mixer;
public void SetMusicVolume(float value) {
SetVolume("MusicVolume", value);
}
public void SetSfxVolume(float value) {
SetVolume("SfxVolume", value);
}
private void SetVolume(string parameter, float value) {
mixer.SetFloat(parameter, value);
}
}
- Go to your audio sources, and choose the proper
Output
to route through. You can still use the "Volume" slider as well, it will just reduce the volume even further.