如何在每个场景中静音声音/音乐



im在Unity3d中创建一个小游戏。这个游戏有4个场景。我创建了小型声音服务,以在游戏中播放/静音/取消静音和音乐。我的大多数声音都是通过游戏中的某些方法播放的,并且通过单击按钮来播放一个声音。

这是我的声音:

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();
}
}

问题是:当我在场景之间移动时,efxsource.mute and Musicsource.mute总是切换到false。

我想在主菜单中静音时,然后开始新游戏,音乐仍然静音。

您可以做的是将状态保存在playerprefs.setint中。您可以拥有值0的值,即其静音和值1的值1。

这样做的好是,即使用户关闭了应用程序,它们也会保留这些值。

您可以使用SceneManager并获取Event SceneManager。https://docs.unity3d.com/scriptreference/scenemanagement.scenemanager.html

,然后:

SceneManager.sceneLoaded -= OnSceneWasLoaded;
SceneManager.sceneLoaded += OnSceneWasLoaded;
public virtual void OnSceneWasLoaded(Scene scene, LoadSceneMode mode)
{
            // TODO
}