Domanda

I have an animation collection with a scene select menu. I've put together a music button that works fine. I use a boolean to determine if the music is on or off, on each scenes. The problem is that the declaration of the boolean is on the first frame of the menu scene and every time an animation finishes, it returns to the first frame of the menu scene and the declaration overwrites the status of the boolean. So if the boolean is changed later in the menu or during one of the animations, every time the menu replays the boolean is restored to its declared value.

Is there a method to prevent variable redeclaration in a repeating frame, or a command to count how many times the frame was played, I can use to skip variable declaration?

Code used:

//Stop other scene sounds
SoundMixer.stopAll();

//music variables
var mutemusic_bln:Boolean = new Boolean();
var menubackgroundmusic:Sound = new menu_mp3();
var music_cnl:SoundChannel = new SoundChannel();
var music_trn:SoundTransform = new SoundTransform();
//starting music
if (mutemusic_bln){
    music_cnl= menubackgroundmusic.play();
    music_trn.volume = 1;
    music_cnl.soundTransform = music_trn
}else{
    music_cnl= menubackgroundmusic.play();
    music_trn.volume = 0;
    music_cnl.soundTransform = music_trn
}

I managed to get it working properly by creating a blank scene before the menu scene, with only one blank script frame. I replaced the boolean declaration there and since the animations return to the menu and not the scene before the menu, it won't overwrite the value. Though I would still appreciate a more decent or more professional solution.

È stato utile?

Soluzione

There is no way to prevent a variable from being changed. That's why it's variable :) Constants in other hand are meant to be initialized only once and cannot be changed later on.

The only problem in your logic is using the timeline and executing the same code every time. Your solution is okay. Sometimes people add just a blank key frame, not a whole scene, and at the end of the timeline they put gotoAndPlay(2);. But the idea is exactly the same as you did - cheers for that! :)

Another solution there is to write something similar to this:

if (!this.initialized) {
    // declare everything here, it will be executed only once
    this.initialized = true;
}

What this will do is that it will set a root variable (initialized) to true, and will execute the block only once. The variable won't get changed later on, because there is no code in that frame that will change it again, unlike your code that resets it.

Either ways, the logic is all the same as well as the problem - if you use classes this will almost never happen!

Hope that helps!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top