- Home /
How to properly set audio on and off
In my Main Menu Scene I have an empty gameObject with an audiosource, which the buttons call for a sound when clicked. In the same menu i enable or disable sounds with a button that calls either function of the following script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundFXOff : MonoBehaviour
{
public bool isSoundEnabled = true;
public AudioSource SFX;
public void SoundOFF()
{
SFX.enabled = false;
isSoundEnabled = false;
}
public void SoundON()
{
SFX.enabled = true;
isSoundEnabled = true;
}
}
And have the Audio Source Component from my game object attached to "SFX".
Now in my Main Game Scene i want my playerobjects Movement script to play a sound when it is jumping depending if the bool "isSoundEnabled" is true or false or use the audio source from the gameObject in the main menu. (It already runs a DontDestroyOnLoad script)
Heres the important parts of the player movement script
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public void Update()
//This is the jump mechanism
{
if(isGrounded() && Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
rb.AddForce(0, 0, -ThrustThrottle);
if(//code to make the sound play from wherever)
{
audiosourcevariable.Play()
}
}
}
Preferably id like to be able to change the isSoundEnabled bool also from a pausemenu in the Main game scene. Also i have soundFX and music separated so muting the program wouldn't work. Any help is appreciated, maybe my approach about this i wrong all together.
Answer by ray2yar · Jan 19, 2019 at 11:05 PM
Are you using an AudioMixer? If not - this would be a good use for one. You can expose the volume parameters to script and control master, effect, and music etc volumes individually.
Well this looks just like what im looking for. However is this Audiomixer project wide or only scene wide?
Create one auiomixer. Go through all your audio sources, and assign them to it. There should be an "audio mixer" line in the inspector for each audio source. The audiomixer is controls the entire project. I beleive the changes to volume will then persist between scenes.