- Home /
Turn music off mutes music and sfx and sfx button doesn't do anything !! is something wrong with the script or might be something else?
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class music_control : MonoBehaviour {
[HideInInspector]
public bool[] _music_fx = new bool[2]{true,true};
public AudioSource _theme;
[HideInInspector]
public Sprite[] _textbuttons;
float _vol_default = 1f;
[HideInInspector]
public Button[] _bt = new Button[4];
void Awake(){
_vol_default = _theme.volume;
}
public void _music_change(){
if (_music_fx [0]) {
_music_fx [0] = false;
_bt[0].GetComponent<Image>().sprite = _textbuttons [0];
_bt[1].GetComponent<Image>().sprite = _textbuttons [0];
_theme.volume = 0f;
} else {
_music_fx [0] = true;
_theme.volume = _vol_default;
_bt[0].GetComponent<Image>().sprite = _textbuttons [1];
_bt[1].GetComponent<Image>().sprite = _textbuttons [1];
}
}
public void _fx_change(){
if (_music_fx [1]) {
_music_fx [1] = false;
_bt[2].GetComponent<Image>().sprite = _textbuttons [2];
_bt[3].GetComponent<Image>().sprite = _textbuttons [2];
} else {
_music_fx [1] = true;
_bt[2].GetComponent<Image>().sprite = _textbuttons [3];
_bt[3].GetComponent<Image>().sprite = _textbuttons [3];
}
}
public void _play (AudioSource _sound, int _typ = 0){
if (_typ == 0) {
if (_music_fx [1]) {
_sound.Play ();
}
} else {
if (_music_fx [0]) {
_sound.Play ();
}
}
}
public void _resetmusic(){
if(_music_fx [0]){
_theme.Play();
}
}
}
Using an array to make the component generic is interesting, but there it's just confusing as you still a method for music and another for sfx. If I may, your code is pretty hard to read with all those _underscores everywhere.
yes that's when I start to name game objects but I am removing the underscores later, do you think there's a better way to do the music and sfx buttons on and off? Thanks for your input.
Hi, this will work fine. Although, sooner or later, you'll want to use this in another project. I usually prefer to make a component that handles sound levels with properties, or indexers if you have a varying number of audio channels, then have buttons simply trigger methods via their onClick events. I touch on this in my first course. There's more info on my website.
Answer by waverz · Jul 04, 2017 at 09:29 PM
It was my mistake the 0 and 1 were opposite.
public void _play (AudioSource _sound, int _typ = 0){
if (_typ == 0) {
if (_music_fx [0]) {
_sound.Play ();
}
} else {
if (_music_fx [1]) {
_sound.Play ();
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Audio Scripting 1 Answer
Add a Play Next Song And A shuffle Option To Music Player C# 1 Answer