The volume control bar in Unity.

Tram Ho

Hi guys, I’ll see you again ^ _ ^

Today I will guide you to create the volume control bar, you can set it in settings, and the user can adjust the volume according to their needs!

Step 1: Create a slide bar.

  • Right-click in the Hierarchy window -> select UI -> Select slider.

Step 2: Add sound.

  • At the Camera object, you add the Audio Source component.

  • At Audio Source component you click on AudioClip -> choose a sound file you have prepared.
  • Press the play button in Unity to check if the sound is playing or not.

Step 3: Adjust the volume according to the slider.

  • Select the slider in the Hierarchy window, at the Slider component you will see the On Value Changed (Single) section.
  • You click the + sign and then drag Main Camera to the None (Object) position of On Value Changed (Single).

  • In On Value Changed (Single) you see the dropbox “No Function”, click on it and select AudioSource -> volume.

  • Press the play button in Unity, when the sound goes off, try dragging the slider on the screen to see the sound change with your slider!

Step 4: Apply to all game sounds.

  • The problem is, what if we have more than 1 sound playing at the same time? This will require a lot of preparation in advance, and it is inflexible if the number of sounds produced at a time is unknown.
  • We have 2 ways, 1 is to adjust the volume of the device (phone), and the second way is to adjust the volume of the audio files before being played. We will use method 2, method 1 sounds a bit negative, right ^ _ ^
  • In order to apply settings to all sounds in the game, we first need a script to manage those sounds.
  • You create a script called SoundManager with the following content:

  • Add this script to Main Camera.
  • You choose the Slider again, at On Value Changed (Single) you choose to dropbox Function before, then choose SoundManager -> ChangeVolume.
  • Try adding an AudioSource component to the Main Camera, then choose an AudioClip for it, then press play and try to pull the Slider.
  • Now you can freely create as many AudioSource in the Main Camera object by Script or manually in the Editor, but when dragging the other Slider it will change the volume as you like!

Wish you all success ^ _ ^

Share the news now

Source : Viblo