Having problem with two audiosources on one object...

Hi guys,

I have one object which has two audio sources. First one is for in-game musics, second one is for sound effects. I have two sliders that supposed to control volumes.

I have assigned audio sources on object via drag-drop on inspector. But two sliders are controlling first audio source. What am i missing?

Hey! :)

First of, i recommend you to use a Music Mixer becouse later on im sure you will want to have an "Overall Music" slider,

aside, we need to see some code in case to help you,
its ok if you have an Object with 2 Audio Sources, but how do you assign them,
how do you add the Functions to modify the Volume?

Hi @Terraya thanks for reply. I made two audio source variable and then assigned them on inspector by drag-drop. I have written this code. I feel like it should work but not sure though...

    private void Start()
    {
        SceneManager.activeSceneChanged += SceneManager_activeSceneChanged;

        musicVolume.onValueChanged.AddListener(delegate {
            MusicSlider();
        });

        soundVolume.onValueChanged.AddListener(delegate {
            SoundSlider();
        });
    }

    public void MusicSlider()
    {
        PlayerPrefs.SetFloat("musicVolume", musicVolume.value);
        audioSourceMusics.volume = PlayerPrefs.GetFloat("musicVolume", musicVolume.value);
    }

    public void SoundSlider()
    {
        PlayerPrefs.SetFloat("soundVolume", soundVolume.value);
        audioSourceMusics.volume = PlayerPrefs.GetFloat("soundVolume", soundVolume.value);
    }

Well,
i would recommend you doing 2 different Objects with a specific name,
- Ambient Sound Handler
- Music Sound Handler

and maybe a third one with

  • Overall Sound Handler,

if you have both AudioSources on 1 GameObject, how does Unity get to know, which to use for what? :)

you should either split them up by Code or Create two Empty GameObjects and assign them then :)

@Terraya looks like i was confused about variable names. I used same variable twice. I fixed it and it's working the way i like. Thanks for suggestions, i will keep them in my mind. :)

6330867--702594--dfsds.png

1 Like