How do I restart flash application with actionscript 3 - actionscript-3

yeah, I need to restart my application, my actioscript 3 code or at least remove all the content in stage to upload the beginning.
This is not movie, so playing with gotoandplays is not an option.
Thanks!

Best practice would be for each object that carries a strong listener to also listen for the Event.REMOVED_FROM_STAGE event, and destroy all its listeners and handle the properties you wish to save.
while(numChildren) removeChildAt(0);
Called from the root (or main timeline) will remove all symbols from the current container in scope. I assume what you're calling it in is added to the display list, so
while(MovieClip(root).numChildren) MovieClip(root).removeChildAt(0);
Is appropriate code.

First structure design.
For example: make a gameContainer the sprite variable add to stage. while the game progresses, all object add gameContainer. When the game is ended, remove the event, you do not need to remove all the objects. And calls the function that default settings you have made that.
// removeEventListener
// removeAllObjects about following
while (gameContainer.numChildren)
{
   gameContainer.removeChildAt (0);
}

Related

AS3 Should i removeEventListener

I have a pretty complex game with many views and many controllers, and it works really well but periodically lags. I am trying to fix up my code so it's as efficient as i can make it, but i have some questions as to who AS3 handles events.
Now here is a very basic example:
AppController loads 5 different OverlayControllers. Each one of those OverlayControllers dispatch an Event.COMPLETE when they are done that my AppController listens to. I have a constant EventListener listening to those OverlayControlllers no matter where I am in the game.
Should i only have those listeners there when the Overlay is open? And Remove them when they close?
Should i bypass the event listener period and just pass the AppController to the OverlayControllers so it can just call a public function instead of requiring an EventListener?
Just to be clear these aren't objects that i'm removing from the stage. They are just being hidden. If i ever remove an object i always remove its event listeners before destroying them.
First of all download Adobe Scout (http://www.adobe.com/devnet/scout/articles/adobe-scout-getting-started.html) and see what's causing the "lags" - probably garbage collection ...then fix the issue. Removing as many listeners as possible is always a good thing but make sure that those are causing the issue. Profile memory usage and try to keep object creation/destruction to a minimum to avoid garbage collection (during the main game loop).

activating a function of a parent as3

I'm attempting to set up a saving and loading system for a flash game I am creating. At the moment I decided to attempt to get the Save File Selection part of my new game menu to work before I proceeded any further with it. I drew up the 'DifficultySelect' screen (which contains save file selection as well as a few other things) in flash, then converted it into a symbol. I made 10 save file symbols inside of this, and created base actionscript files for them. The entire 'DifficultySelect' becomes a child of my 'Main.as' once you proceed through the title screen. I am trying to have my save file data inside of my Main.as, such as levels, health, progress, etc, as well as which save file is currently in use. However, I am unable to create a way for my Main.as to access a MouseClick function for the save file, as I can't simply have a Savefile0.MouseEvent.CLICK event in my Main.as file, as I am not creating a variable to add it to the stage.
I suppose the tl;dr question version of my situation is: How can I get my Main.as to activate one of its functions when SaveFile0 has been clicked? Also, how do I refer to a child from a parent class?
You ask how to refer to a child from parent, but since the child usually "knows" its parent, I suggest following solution:
Your child (SaveFile) should listen for the event (MouseEvent). Once the event is dispatched, you have two options. Either you can dispatch a custom event on parent or directly invoke a public function of the parent.
This is assuming your SaveFile is a MovieClip added to Main:
Inside SaveFile:
var _parentMC:MovieClip = this.parent as MovieClip;
_parentMC.functionToCall();
The best practice, however is to dispatch a custom event in SaveFile, and listen for it in main:
Inside SaveFile:
var customEvent:Event = new Event("customEvent");
this.dispatchEvent(customEvent);
Inside Main:
saveFile.addEventListener("customEvent",functionToCall();
functionToCall(e:Event):void{
}

Actionscript to play/pause audio on different buttons

I've created a few buttons in Flash. I'm trying to make it so that if you click one button, the audio starts playing for that button. If you click another button, the active audio stops and the new audio of the button you clicked last start playing.
Any help please?
What you're describing is actually quite easy to do.
First things first, I recommend importing the audio into your Flash project. Alternatively, there is a way to play it directly from an external file. This is beyond the scope of my answer, so if you need help on that, you should post a question specifically covering it.
Assuming you have imported the audio file into your Flash project's library, make an as3 instance of it. (Right click the file in the library, click Properties --> ActionScript [tab] --> [Check] Export for ActionScript & [Enter name in] Class)
Now, create a definition of the sound in your code. (Assuming your two sounds were named "mySound1" and "mySound2" in the Class field of the previous step.)
var mySound1:Sound = new mySound1();
var mySound2:Sound = new mySound2();
Now, define your sound channel.
var mySoundChannel:SoundChannel = new SoundChannel();
There are two alternate ways of stopping one sound and playing another. The first is to create one function that does both every time. The second method is to create two formulas, one for "play" and one for "stop". You will need to decide which method works best for you. I'll use the two-function method below:
function stopSound():void
{
//This stops all sound in the sound channel.
//If there is nothing playing, nothing happens.
mySoundChannel.stop();
}
//In this function, we create an argument that allows us to tell the function
//what sound to we want it to play.
function playSound(soundname:String):void
{
mySoundChannel = this[soundname].play(0, 0);
}
[Note, you can tweak the play() properties to meet your needs, doing things like starting in the middle of the song, or looping it forever. 0,0 starts at the beginning, and doesn't loop. See the documentation for this.]
Now you hook up the event listeners for the buttons. (If you need help with event listeners, read the documentation.)
myButton1.addEventListener(Mouse.CLICK, btn1Click);
myButton2.addEventListener(Mouse.CLICK, btn2Click);
function btn1Click(evt:Event):void
{
stopSound();
playSound(mySound1);
}
function btn2Click(evt:Event):void
{
stopSound();
playSound(mySound2);
}
This should be enough information to get you started. In my game core, I actually have a custom class for dealing with sound playback that gives me the ability to repeat sounds, change volume, and keep sounds from conflicting with each other. I say that to emphasize that you can do quite a bit with the sound class. Do some digging in that documentation for ideas and help.
You may also consider putting a try-catch statement in the playSound function, since it will throw an reference error if you pass a name for a sound that doesn't exist.

ActionScript 3 Removing All RESIZE Event Listeners

I'm working on a Flash project which is separated into separate scenes.
In Scene 1 I have multiple MovieClips (which include event listeners for RESIZE (and others) inside them).
In Scene 2 I have a few common MovieClips and new ones (which also include event listeners for RESIZE (and others) inside them).
After clicking a button from Scene 1 to go to Scene 2, it's fine, except for if I resize the stage and then I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
I know it's related to the event listeners, but it would be unrealistic to remove them each individually as it's expected there will be many.
If I undertand your situation correctly, I think you will in the end need to remove each listener individually, or add the resize listener only once. Since you mentioned scenes, am I right to assume you are working on the timeline? I also am assuming the null object reference error comes from a scene that has been removed from the stage, making reference to a display object that is no more, a ref to the stage after the scene has been removed, or just calling a function (the resize handler) on an object that no longer exists.
Some way to deal with this are:
Add some checking in the listener handler functions
if (!this.stage) return
To avoid the errors, but will not help if the object the function is a method of has been removed.
To avoid needing remember to remove hundreds of listeners, create removeAllListeners and addCustomEventListener functions. Instead of the usual addEventListener, call you addCustomEventListener which in turn will call addEventListener. Have addCustomListener store the target, listener function and event string in a dictionary or array of objects. removeAllListeners can loop through the dictionary or array and remove all your listeners. It is a bit like setting up an event hub, but does not go quite that far.
Instead of adding the RESIZE event listener to each scene, add it only once. Then in the listener function call a function on whichever scene is the active scene or view.
This last one is the approach I have seen most often, and is the most bullet proof. It may be tricky to implement on the time line, I have always been a little hazy on timeline variable scope.
Yes, so far as I know there is no good automated way to do this, however it would be a good practice to create a registerAllListeners and a removeAllListeners methods that manually add and remove the appropriate listeners to your object.

Unloading external SWF files

I'm loading multiple swf files from the main menu which is never unloaded. I've done this with the following code... Only issue is that instead of unloading to the main menu I just see a white screen as if nothing is loaded.
function BackToMenu(i:MouseEvent):void
{
var BaseMovie:MovieClip = parent.parent as MovieClip;
BaseMovie.parent.removeChild(BaseMovie);
}
EDIT: I'll explain from the start I have a MainMenu.swf. The games are loaded from MainMenu.swf when the button relating to the game is clicked. When a game button is clicked on MainMenu.swf the game loads. When the player completes a game they are presented with the exit button which unloads the current game and shows the MainMenu.swf without having to re-load it.
First, you should remove one parent to make sure you are actually removing only the game:
function BackToMenu(i:MouseEvent):void
{
var BaseMovie:MovieClip = parent as MovieClip;
BaseMovie.parent.removeChild(BaseMovie);
}
This should take care of your most pressing problem, and allow you to return to the menu. You have, however, not really unloaded the game, but only removed it from the display list. This often means, that there are still sounds running, active key and/or mouse listeners, etc. - these must all be taken care of!
And, like I said, this will only fix your immediate problem. It is, however, neither a permanent solution, nor a good one: Since the main SWF is responsible for loading the games, it should also be responsible for disposing of them. You should put cleanup code into your game, but it should only be concerned with stopping any running scripts, sounds, etc. - simple rule: anything that is started within the game, should be stopped within the game. But it should not try to access objects further up in the display hierarchy, or try to unload itself.
The much better way to do this is by replacing all the above code, and letting the main SWF take care of removing the game, as well as unloading it from memory. For this, you have to do three things:
Instead of writing actual removeChild calls, etc., let your button dispatch a custom event to notify the main SWF that it should now be removed:
function onBackButtonClicked( event:MouseEvent ):void {
destroyGame(); // this would be the function that stops all the scripts
dispatchEvent( new Event( "FINISH_GAME", true ) );
}
Note that "FINISH_GAME" is now a "bubbling" event, i.e. it travels downward in the display hierarchy. We can now listen for this event in any ancestor display object containing the game.
In your main SWF, add an event listener to the Loader when the game was successfully loaded. This is done in the event listener that is called when the load process completes:
function onLoadComplete( event:Event ):void {
var loader:Loader = event.target.loader;
loader.addEventListener( "FINISH_GAME", onFinishGame, true );
}
Use the corresponding event handler to remove the game clip:
function onFinishGame( event:Event ):void {
var loader:loader = event.currentTarget;
loader.parent.removeChild( loader );
loader.unloadAndStop();
}
A few more things to consider:
The naming conventions in ActionScript advise us to use lower case names for methods and variables, and upper case only for types.
The same naming conventions suggest we use either "on" or "handle" as a prefix for event listeners, along with the name of the event. Thus, it should be onBackToMenu or rather, onBackButtonClicked, etc.
Since I don't know anything about the code you use for loading, I just assumed you have a complete listener, and you don't keep references to the loader. If you use a member variable, you can use that instead of event.target, resp. event.currentTarget.