V
V
vkvk2020-12-12 20:53:43
Unity
vkvk, 2020-12-12 20:53:43

How to add background music to each scene and customize it?

Hello! I'm creating my first game, and then I ran into a problem. I added music to the game, made it so that it is configured using a slider, but when there is a transition between prices, it disappears, and at the beginning of the game it is also not there. Can you please help? I couldn’t find an answer on YouTube, and I don’t really like the game without sounds.

Here is the code I used

{
    [SerializeField]private AudioSource audio;
    private Slider slider;

    [SerializeField]private string saveVolume;

    [SerializeField]private string sliderTag;

    private float volume;

    private void LateUpdate()
    {
        GameObject sliderObj = GameObject.FindWithTag(this.sliderTag);
        if (sliderObj != null)
        {
            this.slider = GetComponent<Slider>();
            this.volume = slider.value;

            if (this.audio.volume != this.volume)
            {
                PlayerPrefs.SetFloat(this.saveVolume, this.volume);
            }
            this.audio.volume = this.volume;
        }
    }
    private void Awake()
    {
        if (PlayerPrefs.HasKey(saveVolume))
        {
            this.volume = PlayerPrefs.GetFloat(saveVolume);
            this.audio.volume = this.volume;

            GameObject sliderObj = GameObject.FindWithTag(this.sliderTag);
            if (sliderObj != null)
            {
                this.slider = sliderObj.GetComponent<Slider>();
                this.slider.value = this.volume;
            }
            else
            {
                this.volume = 0.5f;
                PlayerPrefs.SetFloat(this.saveVolume, this.volume);
                this.audio.volume = this.volume;
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-12-13
@vkvk

Does it hang on the object (music)? Throw a script on it and write in it: https://docs.unity3d.com/ru/530/ScriptReference/Ob...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question