x


Audio toggle switch is silent on first button press?

I have created a button that starts playing a loop when it is pressed. That was simple to do! Now I've been looking for an elegant way to just click that same button again and stop the loop. I searched through the forums and found a clever hack to do this, by just muting the volume if the volume is 1.0 and increasing it if it is 0.0. However this isn't working exactly as I had planned! On the 1st click of the button there is no audio. Only on the 3rd click does the audio show up. I think I understand why it is not working but I'm not sure what is really the best solution in this case. I have tried a couple other approaches, but so far I've not figured it out.

var sound : AudioClip;

function OnMouseDown() {
 audio.Play(); 

if (audio.volume == 1.0)
audio.volume = 0.0;
else
audio.volume = 1.0;

 }

Thanks!

EDITED/HERE IS THE FIXED AUDIO TOGGLE BELOW/

var sound : AudioClip;

var onoff = false;

function OnMouseDown() {

if (!onoff) {

audio.Play();

} else {

audio.Stop(); }

onoff = !onoff;

}

more ▼

asked Aug 04 '12 at 01:35 AM

Glark gravatar image

Glark
9 1 2 5

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

It may not be 1 or 0 at start, check the Inspector, but you know, there is a 'mute' field you can set true or false.

more ▼

answered Aug 04 '12 at 01:36 AM

DaveA gravatar image

DaveA
26.5k 151 171 256

Ah, thanks! I did check that out. And then spent some more time looking into if / else, finally managed to find one that worked. Although, I am not 100% sure how it is working and the logical structure behind it.

var sound : AudioClip;

var onoff = false;

function OnMouseDown() {

if (!onoff) {

audio.Play();

} else {

audio.Stop(); }

onoff = !onoff;

}

Aug 04 '12 at 02:55 AM Glark
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1029
x162
x8

asked: Aug 04 '12 at 01:35 AM

Seen: 287 times

Last Updated: Aug 04 '12 at 02:57 AM