AS3: Major Slowdown - actionscript-3

I'm working on a Flash game, and after running my game for a while there is a huge drop in frame rate. There aren't a lot of MovieClips onscreen at once, but MovieClips are being replaced using removeChild and addChild often.
How can one test for problems such as memory leaks? And what are some good AS3 programming standards on this matter?

It seems like you're not preparing your instances of MovieClip for garbage collection. This thread could be extremely helpful to you.
Some of the basic things you want to cover when discarding a MovieClip (or any other Object) properly are:
Remove the object from the DisplayList (if it's a DisplayObject). This is done via what you're doing already, removeChild()
Remove any event listeners that have been applied to the Object. Best thing to do is keep on top of this right from the beginning; by that I mean, when you call addEventListener(), be sure to somewhere in the very near future add a sister removeEventListener() as well.
Remove reference to your Object. This includes, but is not limited to: reference to the Object via being part of an Array/Vector, reference via being stored in a property of another Object, etc.
A suggestion that I can offer is to have in the base class of your objects a method that handles all of this, eg remove() or deconstruct().
Here's an example:
public function deconstruct():void
{
if(parent)
parent.removeChild(this);
removeEventListener(MouseEvent.CLICK, _onClick);
}
And when you extend this class and need other dereferencing features, just build on your deconstruct() method:
override public function deconstruct():void
{
removeEventListener(MouseEvent.MOUSE_OVER, _mouseOver);
var i:int = someArray.indexOf(this);
someArray.splice(i, 1);
super.deconstruct();
}

http://gskinner.com/talks/resource-management/

Related

Model-view design in Flash

I'm creating a simple game to learn Flash programming. To have a clean model/view separation, I want to create a Player class which simply holds data relevant to the user. I'm also creating a StatusView class which extends MovieClip and which coresponds to a movie clip symbol which I've created in my Flash project. Basically the StatusView will display the data of my Player class onscreen.
I'm used to doing this sort of thing using listeners, so I've found the EventDispatcher class and added one as a member of my Player class. I'd like to have my StatusView movie clip add an event listener to my Player class so that it can receive messages whenever I change the data in my Player class.
The problem is, there doesn't seem to be anywhere for me to put my Player class so that the StatusView can find it (to add the listener). Everything in the project is created directly by one of the movie clips, and the runtime seems to create these movie clips in an arbitrary order. For example, say I create a MovieClip symbol called GameView and I create the instance of the Player there, and GameView is the parent of StatusView. When StatusView is constructed, I'd like to be able to access the Player from it's parent, but at that point GameView hasn't had it's constructor code run yet. This is true even if I wait for the ADDED_TO_STAGE event.
I could put the game model code in a singleton, but this seems like a hack to me. Is there a best practices way in Flash that lets me create and access my game model independent of all the MovieClip symbol stuff?
If you want to pass the reference of the Model to the constructor of the View, but are not calling the constructor yourself (because you do not create the object via code) you are out of luck here.
You could instead simply define a method on your View to pass a reference of the Model object:
public function setModel(value:Model):void
usage:
view.setModel(player);
There's no "law" that you have to pass the Model to the constructor of the View.
You can also create a set function for convenience:
public function set model(value:Model):void
usage:
view.model = player;
I feel like I have to disagree on the Singleton. The purpose of a Singleton is to guarantee that there's only one instance of it in existence. That's it.
It is not there to pass reference around easily (because the method to get the single instance is static). This is (IMO) a bad practice.
You could make anythign static in order to pass it around "easily". But this would make a mess and nobody does that.
But suddenly, just because the singleton pattern uses a static method, a lot of people think it's a clever way to get to the reference. I beg to differ.
First of all, you could implement Player class as singleton if you need just one instance. I don't think that that looks like a hack (for example, in PureMVC framework each model is a singleton).
At second, you can create instances of Player class in some general class (manager) and send them to views.
P.S. Also, I want to note that you can extend your Player class from EventDisptacher without creating specific field "eventDispatcher" in Player class. I don't know what way is better, but this one is simpler, imho.

as3 symbol variables not initialized yet

I'm initializing symbols in my timeline, and trying to access the variables within those symbols, but they return 0 or undefined even though I set the variables in the symbol's timeline. For some reason the variables haven't been set yet, though the main timeline can see that they exist. How do I make the program wait until the variables have been set?
Best practice to work with classes, not coding in timeline and frames of MovieClip.
I assume you have MovieClip from designer and you want inject some logic to the specific frame. There are many options.
Events
You can trigger event in the specific frame, and you work in normal way (with classes and class members).
//Frame code
import flash.events.Event;
this.dispatchEvent(new Event("IntroDidFinish", true, true));
stop();
//Somewhere in class
myContainer.addEventListener("IntroDidFinish", onIntroFinish, false, 0, true);
function onIntroFinish(e: Event):void{
//Do your stuff
}
Events help you decouple logic from the design(predefined complex MovieClip, etc.)
Waiting for initialisation
As MovieClip reaches some frame, you should wait extra time for initialisation. Thats why 99.9% of AS3 developers don't like MovieClip as holder for any critical data or logic. It means if you call myMovieClip.goToAndStop(8); you can't get myMovieClip.someValue declared in 8 frame after goTo operation. If you still want to go with such approach, easiest solution for you will be Event.ENTER_FRAME, after goTo subscribe for ENTER_FRAME event, for only one update, and do your work ;)

How do I completely remove a loaded swf and reload it? (Trying to restart a game)

I have a preloader that loads a swf, the swf creates a bunch of listeners, objects, and movie clips. I want all of these to be destroyed and recreated.
Simplified version of my preloader:
var request:URLRequest = new URLRequest("myfile.swf");
var myLoader:Loader = new Loader();
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, function(event){
stage.addChild(myLoader);
myLoader.loadBytes(urlLoader.data);
});
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load(request);
When I try to remove it, I do this:
stage.removeChild(myLoader);
var child = loader.myLoader.content as Object;
SoundMixer.stopAll();
while(stage.numChildren > 0){
stage.removeChildAt(0);
}
child.stop();
while(stage.numChildren > 0){
stage.removeChildAt(0);
}
child=null;
System.gc();
myLoader.unloadAndStop(true);
System.gc();
myLoader.unload();
System.gc();
myLoader.loadBytes(urlLoader.data);
stage.addChild(loader.myLoader);
In your loaded SWF you may create a method 'destroy' which would remove all listeners, destroy all objects and reset all data.
You can call this method either from the parent object (if the method is public) or you can call destroy when you remove the SWF from stage (Event.REMOVED_FROM_STAGE)
You can reload swf with js, this is the easy way to do this. you can check this answer.
Or you have to do a good object and listener managment and reset game in swf file. This might be complex as project get bigger. You need release methods that removes all references and listener.
first you should load your swf using the Loader Class like this :
var movie:MovieClip
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
loader.load( new URLRequest("myfile.swf"));
function loadComplete(event:Event):void
{
movie = loader.content as MovieCLip;
addChild(movie);
}
//when reloading just remove the movie object from the stage
removeChild(movie);
SoundMixer.stopAll();
//......
//.
//.
I know this is old, but I stumbled on it for reference and see some things that I think should be mentioned.
System.gc() - while it's a function you have access to, everything I've seen suggests that the garbage collector should never be called by your code unless you've used a considerable amount of memory and need it back immediately. The garbage collector usually has a better idea of when it should run than you do (Force Garbage Collection in AS3?). It can impact performance for not just your application but all flash applications running in that browser or container.
There's also a good bit of people struggling to make effective use of unloadAndStop(), as it seems to be rather unreliable in various contexts (Unloading swf using the unloadAndStop() method, but video sounds remain audible).
To be thorough, I'd strongly suggest putting the effort into simply eliminating everything as it would be in any other language from within the loaded flash object first before removing the flash object itself, not expecting the container to take care of it for you. This is why Flash has a reputation for memory leaks to begin with.
Inside the loaded swf, add code that fires on unload.
One way is to add this to the swf:
this.addEventListener(Event.REMOVED_FROM_STAGE, doUnload)
Then have the doUnload functon perform the following:
Use removeEventListener to effectively terminate the event handlers. You could either recall all the addEventListeners you created, or cook up a routine to walk through and remove them all by traversing the objects in play. The first option is more efficient since it's exclusive, but the second option would theoretically be something you could memorize and copy between applications.
Use delete() on variables to make them removable by the garbage collector. NOTE: Unlike many languages, a referenced variable will not be removable unless the reference is also removed. For example:
var a:int = 0;
var b:int = a;
delete(a); // b still exists and equals 0, a is not available to GC.
delete(b); // now both variables can be removed by GC.
There's also still confusion as to whether it's a good idea to use removeChildAt(0) or remove the child objects individually. The first has the benefit of being distinctly simple and straight-forward, but that also gives it the caveat of not being entirely understood by the coder, and possibly missing something similarly to unloadAndStop(). Not as much as walking your object tree with removeChild and eliminating things explicitly without question or uncertainty.
After this is set, adding a function to unload the flash object will trigger its self-removal, so the loader will remain simple and neat, and reload the flash cleanly.

AS3 scope and garbage collection

Objetcs created inside a function are automatically marked for garbage collection if not referenced anywhere else?
Let´s say, I have a class called SubClass. in the constructor I create some displayObjects.
Then I instatiate SubClass somewhere. When I remove this SubClass instance, will the objects inside be marked for garbage collection?
thanks in advance!
cheers
Bruno
Yes, unless you have references to SubClass's members anywhere outside SubClass, or you keep an active reference to the outside of your class from within SubClass (or any objects within it).
A typical example of the latter is if SubClass subscribes to a Stage event; if the listener is not weak (5th argument of addEventListener) you will keep an active link between the stage and your SubClass instance, and even if you remove the object and null it, it will not be collected.
For simple listeners you can set that 5th argument to true, so the reference is weak and will be broken by the garbage collector. For more complex situations (or for example NetStreams, Loaders, Timeline audio, etc...), you need to create a way for the class to unlink itself for any outside objects and stop any process that could prevent collection, like a public destroy() method that closes requests, stopping media, removeListeners, etc...
But then again, for simple situations when you only have isolated childs, and no references to the outside of your class, simply removing your instance and nulling its reference should be enough for the garbage collection.

Memory management AS3

My AS3 application basically does the following (pseudo code from main application class) 3 or 4 times by adding custom objects to stage:
_movieClipClassVariable = new MyCustomSpriteSubclass();
_movieClipClassVariable.addEventListener(MyEvents.READY, function(event:Event):void {
_hideLoading();
mcHolder.addChild(_movieClipClassVariable);
});
_movieClipClassVariable.addEventListener(MouseEvent.CLICK, myClickHandler);
private function coverClickHandler(event:Event):void
{
...
}
What is the right way to allow Garbage Collector to recycle _movieClipClassVariable after it is not necessary? Assign null to it? Remove all listeners? Use weak reference for listeners?
Thanks in advance!
I would say all of the above.
I recommend reading Grant Skinners articles of Resource Management. Also take a look at his slides from his Resource management talk.
There is quite a lot of information out there on this subject, and those two links are the best resources I have found.
In order to get use of garbage collector you should consider:
Not defining handler methods inside the X.addEventListener() call
Remove all event listeners on the object you want to free up from memory
Make the object null
4.(optional) you can force garbage collector calling system.gc();