Turn Off Sound And Music Individually?

As you read in the title, I want to know how to turn off the sound of my game, without turning off the music, and if I want to turn off the music, it will not affect the sound. So far, I haven’t been able to do so. I’ve only been able to turn off both the sound and music by using AudioListener.volume = 0;, but not individually. So how can I do it?

I have only two audio sounds. One for the jump sound which is part of my character controller, and the music audio which is a different script itself, on a different gameobject. Here’s my menu script in which I use to turn off the sound: http://pastebin.com/5agXeq65 Here’s the Music Script: http://pastebin.com/3B7YQJ9k And finally the jump script which again is apart of my character controller script. I only took it out because my character controller script is too big for you guys to read: http://pastebin.com/2NRKyyaH

Please help with what I have here if you want to. I’ve haven’t been able to figure out how to do this correctly for about a month now.

You can disable each AudioSource (that is, the same thing you’re using to play the music/sounds in the first place) by setting audio.volume to 0, or audio.enabled to false, or audio.Pause().

Thank you. I will try it out. EDIT: Alright I have a question. How can I get the audiosource, from a different scene? The sound menu script I posted is in a different scene than the jump sound and music audio. It also is on a different gameobject, so how can I disable the audiosource of a different scene from the sound menu? I’ll post pictures to show you.

EDIT2: Alright here’s some pictures: First the Sound Menu Scene, the picture is of the main camera in that scene with the sound menu script attached to it: http://imgur.com/kCY7OtC
Next is the jump audio, which is located in a different scene that has the player in it(it’s the game itself). The picture shows only a little bit of the character controller. The jump audio is apart of it: http://imgur.com/Y96FwGW
Last is the music script, which is on an empty gamobject named music attached to the Player GameObject. http://imgur.com/a3lyJP2

I suggest you create an AudioManager and pool your effects. This way you can switch off / turn down the volume of your objects at will.

Interesting, I never used that before. I’ll see what I can do with it. Thanks for the suggestion.

What you would want is something like this.

using UnityEngine;
using System.Collections;

public sealed class AudioManager : MonoBehaviour {
    private static readonly string _tag = "Audio Manager"; // You need to create this.
    private static AudioManager _instance = null; // Cache for single instantiation.

    private AudioManager() { } // Private constructor.

    public static AudioManager AudioInstance {
        get {
            if(AudioManager._instance == null) {
                GameObject audioManager = GameObject.FindGameObjectWithTag(AudioManager._tag);

                if(audioManager != null) {
                    AudioManager._instance = audioManager.GetComponent<AudioManager>();
                }

                if(AudioManager._instance == null) {
                    Debug.LogError(typeof(AudioManager).ToString() + " - AudioInstance: Could not find scene instance with tag '" + AudioManager._tag + "'");
                }
            }

            return AudioManager._instance;
        }
    }

    public AudioItem[] musicAudio = new AudioItem[0];
    public AudioItem[] soundEffects = new AudioItem[0];

    public void PlayMusic(string audioName) {
        this.PlayMusic(audioName, 3.0f);
    }

    public void PlayMusic(string audioName, float crossFade) {
        this.PlayMusic(audioName, crossFade, default(Vector3));
    }

    public void PlayMusic(string audioName, float crossFade, Vector3 position) {
        foreach(AudioItem musicItem in this.musicAudio) {
            if(musicItem.audioName == audioName) {
                // Play audio add the effects I listed above. We could go into more detail but this is what I would do.
            }
        }
    }

}

[System.Serializable]
public class AudioItem : System.Object {
    public string audioName = ""; // Name to be used to call the audio clip.
    public AudioClip audioClip; // Actual audio item.
}

I whipped this up right now but hopefully you get the basics behind what you can accomplish here. Ideally you would want to make a prefab so it can persistent throughout all the scenes and pool your audio sources.

1 Like

Yeah I was reading more about it and I am currently doing a tutorial available on Unity. Thanks for the script and explanation though it really helps me understand it even more. I’ll see if I can get it to work the way I want after I finish the tutorial. Thanks again.

No worries if you need any help just post.

Okay so I finished the tutorial and messed around with the script you posted. So I created a empty GameObject with your script attached and a Audio Source. After setting up what I wanted in the inspector I turned it into a prefab like you suggested. Now the thing is, I’m a little confused with you script. I know how to work the inspector part of it, but not actually getting the audio to play. I’ve created a test script to see if it would play any audio, and the problem is, is that I don’t know how to. I know in your script you said “// Play audio add the effects I listed above. We could go into more detail but this is what I would do.” but I’m not sure which ones to add. Here’s my test script that’s attached to the prefab:

public class Test01 : MonoBehaviour {

    public AudioItem[] soundEffects = new AudioItem[0];

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
   
        if(Input.GetKeyDown (KeyCode.Space))
        {
            //Play Audio
            //I tried GameObject.Find("Audio Manager").SendMessage ("Play", "Jump"); doesn't work
            //I tried this.PlayMusic(audioName, 3.0f); or something along those lines, doesn't work
            //I know I'm doing it wrong, it's obvious thanks to the error I get:
            //ERROR: SendMessage Play has no receiver! UnityEngine.GameObject:SendMessage(String, Object)
        }
    }
}

I hope I’m not asking for too much, but if you don’t mind can you go into a little more detail on how to play certain audio clips? My understanding of your script is a little messy.:face_with_spiral_eyes:

Lol no worries, what you have to do is instantiate them then pool them. By pooling you can play them whenever you need to at will and disable them whenever you need to. Let me write something up really quick.

1 Like

But what do I instantiate and pool? The audio itself or something else?

Alright so you still there?

Well if you are there, what you need to do is pool your audio clips onto a prefab. So what you want to do is instantiate a prefab with an AudioSource component attached to it. What I did was create a simple script (which you can add to it) that I attached to my AudioItem.prefab.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class AudioItemSource : MonoBehaviour {
    private string audioName;
    private bool isPlaying;

    public string AudioName {
        get {
            return this.audioName;
        } set {
            this.audioName = value;
        }
    }

    public bool IsPlaying {
        get {
            return this.isPlaying;
        } set {
            this.isPlaying = value;
        }
    }

    public void Play() {
        this.GetComponent<AudioSource>().Play();
    }
}

Create a prefab name it whatever you want then attach this script to it.

AudioManager:

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

public sealed class AudioManager : MonoBehaviour {
    private static readonly string _tag = "Audio Manager"; // You need to create this.
    private static AudioManager _instance = null; // Cache for single instansitation.

    private AudioManager() { } // Private constrictor.

    public static AudioManager AudioInstance {
        get {
            if(AudioManager._instance == null) {
                GameObject audioManager = GameObject.FindGameObjectWithTag(AudioManager._tag);

                if(audioManager != null) {
                    AudioManager._instance = audioManager.GetComponent<AudioManager>();
                }

                if(AudioManager._instance == null) {
                    Debug.LogError(typeof(AudioManager).ToString() + " - AudioInstance: Could not find scene instance with tag '" + AudioManager._tag + "'");
                }
            }

            return AudioManager._instance;
        }
    }

    public GameObject audioPredab;
    public AudioItem[] musicAudio = new AudioItem[0];
    public AudioItem[] soundEffects = new AudioItem[0];
    private List<GameObject> musicPool = new List<GameObject>();
    private List<GameObject> soundEffectsPool = new List<GameObject>();

    void Start() {
        this.PoolMusic();
        this.StartCoroutine (TestPlay ());
    }

    IEnumerator TestPlay() {
        yield return new WaitForSeconds(5.0f);
        Debug.Log ("Invoked!");
        this.PlayMusic("Intro");
    }

    public void PlayMusic(string audioName) {
        this.PlayMusic(audioName, 3.0f);
    }

    public void PlayMusic(string audioName, float crossFade) {
        this.PlayMusic(audioName, crossFade, default(Vector3));
    }

    public void PlayMusic(string audioName, float crossFade, Vector3 position) {
        foreach(AudioItem musicItem in this.musicAudio) {
            if(musicItem.audioName == audioName) {
                foreach(GameObject pooledAudio in this.musicPool) {
                    if(pooledAudio.GetComponent<AudioItemSource>().AudioName == audioName && pooledAudio.GetComponent<AudioItemSource>().IsPlaying == false) {
                        Debug.Log("Playing: " + audioName);
                        pooledAudio.SetActive(true);
                        pooledAudio.GetComponent<AudioItemSource>().Play();
                    }
                }
            }
        }
    }

    public void MuteMusic() {
        foreach(AudioItem audioItem in this.musicAudio) {

        }
    }

    public void UnMuteMusic() {
        foreach(AudioItem audioItem in this.musicAudio) {
            // audioItem.audioClip.mute = false;
        }
    }

    public void MusicVolume(float volume) {
        foreach(AudioItem audioItem in this.musicAudio) {
            // audioItem.audioClip.volume = volume;
        }
    }

    private void PoolMusic() {
        foreach(AudioItem audioItem in this.musicAudio) {
            if(audioItem.audioClip != null) {
                GameObject tempAudio = Instantiate(this.audioPredab, default(Vector3), Quaternion.identity) as GameObject;

                tempAudio.name = "AudioItem::" + audioItem.audioName;
                tempAudio.transform.parent = this.gameObject.transform;
                tempAudio.GetComponent<AudioSource>().audio.clip = audioItem.audioClip;
                tempAudio.GetComponent<AudioItemSource>().AudioName = audioItem.audioName;
                tempAudio.GetComponent<AudioItemSource>().IsPlaying = false;
                tempAudio.SetActive(false);
                this.musicPool.Add(tempAudio);
            }
        }
    }

    private void PoolSoundEffects() {
        // Same as PoolMusic
    }
}

[System.Serializable]
public class AudioItem : System.Object {
    public string audioName = ""; // Name to be used to call the audio clip.
    public AudioClip audioClip; // Actual audio item.
}

Audio Item we have to create this has 2 components AudioItemSource and AudioSource.

Our updates to AudioManager

To play a music track from AudioManager you would use this line of code.

AudioManager.Instance.PlayMusic(“Intro”);

Keep in mind this is not complete so don’t expect it to work 100% this is at 40% working, the rest is up to you unless like I said you need help.

Sorry I had to pick someone up. Anyways wow thanks for this. I’ll get to working on it right away.

Sorry quick question, am I supposed to get errors? You said it was only 40%, so is that what you meant? Errors:

The type or namespace name `List`1' could not be found. Are you missing a using directive or an assembly reference?
The type or namespace name `List`1' could not be found. Are you missing a using directive or an assembly reference?

Did you get all of the ‘using’ lines at the top when you copied the script?

1 Like