1

Im creating a small game in Unity3d. This game have 4 scenes. I created small Sound Service to play/mute/unmute sounds and music in my game. Most of my sounds are played by some methods in the game, and one sound is playing by clicking the buttons.

This is my SoundSerice:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundService : MonoBehaviour
{

public AudioSource efxSource;
public AudioSource musicSource;

public static SoundService instance = null;

public AudioClip dieSound;
public AudioClip pointSound;
public AudioClip newRecordSound;
public AudioClip flapSound;

public void MuteSounds()
{

    if (efxSource.mute)
        efxSource.mute = false;
    else
        efxSource.mute = true;

}



public void MuteMusic()
{
    if (musicSource.mute)
        musicSource.mute = false;
    else
        musicSource.mute = true;
}


void Awake()
{
    if (instance == null)
        instance = this;
    else if(instance != this)
        Destroy(gameObject);

    DontDestroyOnLoad(gameObject);
}

public void PlaySingle(AudioClip clip)
{
        efxSource.clip = clip;
        efxSource.Play();
}

public void PlayLoseSound()
{
    efxSource.clip = dieSound;
    efxSource.Play();
}

public void PlayPointSound()
{
    efxSource.clip = pointSound;
    efxSource.Play();
}

public void PlayFlapSound()
{
    efxSource.clip = flapSound;
    efxSource.Play();
}

public void PlayNewRecordSound()
{
    efxSource.clip = newRecordSound;
    efxSource.Play();
}
}

The problem is: when i'm moving between my scenes, the efxSource.mute and musicSource.mute is always switching to false.

I want to when i mute music in main menu, and then start a new game, the music is still muted.

mmm
  • 260
  • 4
  • 21

2 Answers2

1

What you could do is save the state in PlayerPrefs.setInt. You could have the value 0 for when its muted and the value 1 for when its unmuted.

What's good with this is they will keep those values even if the user closes the application.

I.B
  • 2,925
  • 1
  • 9
  • 22
1

You can use SceneManager and get event SceneManager.sceneLoaded https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html

And then :

SceneManager.sceneLoaded -= OnSceneWasLoaded;
SceneManager.sceneLoaded += OnSceneWasLoaded;

public virtual void OnSceneWasLoaded(Scene scene, LoadSceneMode mode)
{
            // TODO
}
Cổ Chí Tâm
  • 330
  • 1
  • 7