Reputation: 35
I have an object with Audio Source on my "menu" scene and a script is attached to it, in order to keep it playing between scenes without resetting. I'd like to mute/unmute the audio using a button on an options scene and save this setting for every launch of the app if possible for the next steps.
I've made the audio keep playing by attaching a script on the object. Here is the code to keep playing the music through the scenes.
public class dontStopAudio : MonoBehaviour {
void Awake()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("BGAudio");
if (objs.Length > 1)
Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
}
I've tried to create a script to toggle the background music on and off and calling the music game object in order to get the mute component and change it's value but didn't seem to work. I also tried to create a control function with if and if else comparing the value of mute property of the audio source component but i wasn't able to change it in any way.
This is how i tried to do it but i'm sure there is something severely wrong about it. Just can't figure out what, since i'm kind of a beginner on unity and just trying to expand my knowledge with small projects.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class toggleMusic : MonoBehaviour {
public GameObject bgMusic;
public AudioSource bgAudio;
public GameObject toggleMusicButton;
public Sprite soundON, soundOFF;
public void bgMusicOnOff()
{
bgAudio = bgMusic.GetComponent<AudioSource>();
if (bgAudio.mute = false) {
bgAudio.mute = true;
toggleMusicButton.GetComponent<Image>().sprite = soundOFF;
}
else if (bgAudio.mute = true) {
bgAudio.mute = false;
toggleMusicButton.GetComponent<Image>().sprite = soundOFF;
}
}
}
I also tried to call the method on button's OnClick() panel, didn't seem to work as well.
I want to be able to mute/unmute the audio (which is attached to an object only exists in "menu" scene and keeps playing through all scenes with the script I've shared) from the "options" scene using a button and after i successfully done it, i might proceed to save the setting for every time user launches the app.
Thank you so much for your time in advance, i know there is something i'm failing to consider but i fail to see what because of my lack of knowledge/experience on Unity
Upvotes: 0
Views: 215
Reputation: 91
You should look up PlayerPrefs.
Then you can use something like:
PlayerPrefs.SetInt("SoundOn", 1);
and
if(PlayerPrefs.GetInt("SoundOn"))
{
//turn sound on
}
else
{
//turn sound off
}
on startup.
Hope this helps.
Upvotes: 1