- Home /
Why is this script not working?
Hello Unity Users! I am trying to manage sound an music in my 2D game and tried this script to start with:
var sound : int = 3;
function OnMouseDown (){
if (sound == 3){
sound = 2; }}
It worked perfectly, when I was clicking the "button", the sound variable was changing to "2". The problem is after that. I tried to develop the script a little more the script, but it stopped working after that! Clicking the button now doesn't change anything and nothing happens after that! Here is my new script:
var sprite0 : Sprite;
var sprite1 : Sprite;
var sprite2 : Sprite;
var sprite3 : Sprite;
var sound : int = 3;
function OnMouseDown (){
if (sound == 3){
sound = 2;
GetComponent(SpriteRenderer).sprite = sprite2;
AudioListener.volume = 0.66; }
if (sound == 2){
sound = 1;
GetComponent(SpriteRenderer).sprite = sprite1;
AudioListener.volume = 0.33; }
if (sound == 1){
sound = 0;
GetComponent(SpriteRenderer).sprite = sprite0;
AudioListener.volume = 0; }
if (sound == 0){
sound = 3;
GetComponent(SpriteRenderer).sprite = sprite3;
AudioListener.volume = 1; }
}
So my question is: What am I doing wrong? Why does the sound value doesn't even change now? What should I change? Thanks for your advices :)
Answer by robertbu · Nov 06, 2014 at 09:23 AM
You need to either put 'else' in front of the 'if' statements on lines 11, 15 and 19, or you need to reorder your 'if' statements. Take a look at what happens. if (sound == 3) you set it to 2, which makes line 11 true changing 'sound' to 1, which amke line 15 true changing 'sound' to 0 which makes line 19 true, which makes 'sound' back to 3. So if 'sound' starts at 3, it will execute the code in every 'if' statement.
wouldn't doing something like this be better? Just asking. Coz I'm not sure if it's better than if statements for this particular case.
switch(sound)
{
case 0:
//set sound to 3 and do something
break;
case 1:
//set sound to 0 and do something
break;
case 2:
//set sound to 1 and do something
break;
case 3:
//set sound to 2 and do something
break;
}
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Mute volume / sound problem 1 Answer
sound too low in Android devices 0 Answers
Sprinting Audio Problem 1 Answer