Reputation: 1984
I am making a platform game in flash.
I have a goal class(the class which contains code for the goal sprite, where when you hit it, it continues to next part of game).
Inside the goal constructor, 2 event listeners are added, they are as follows:
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, eFrame);
The beginClass function is fine, and only runs once, but eFrame is what checks if the player has hit the goal, so it is constantly running. The problem is, once the player hits the goal, eFrame continues to run, while in a menu describing the next scene to the player. My eFrame function is below.
private function eFrame(event:Event):void{
if(hitTestObject(_root.mcMain)){
var lastScore:int = _root.mainScore;
_root.mainScore = lastScore;
while (_root.lvlHolder.numChildren > 0) {
_root.lvlHolder.removeChildAt(0);
}
_root.mcMain.removeChildAt(0);
_root.isInCut = true;
if (_root.lvlCurrent == 1) {
_root.gotoAndStop(2);
} else if (_root.lvlCurrent == 2) {
_root.gotoAndStop(3);
} else if (_root.lvlCurrent == 3) {
_root.gotoAndStop(4);
}
}
}
Frames 2, 3, 4, are frames with just text and a button that display a message to the player, and then the player hits continue. My problem is that eFrame is still trying to be run, but the class has not been instantiated, and the method is causing extreme amounts of lag once the player continues.
Upvotes: 0
Views: 409
Reputation: 811
Inside Goal, what's the point of _root?
Anyway here's what I've done:
Change the event ADDED
to ADDED_TO_STAGE
, that way, when the event is fired we know this Sprite has a stage
property.
addEventListener(Event.ADDED_TO_STAGE, beginClass);
Remove the eFrame
event from the constructor. Add it to beginClass
, with stage
, like so:
stage.addEventListener(Event.ENTER_FRAME, eFrame);
Now in eFrame
, you can awesomely remove the event with the stage reference. It didn't work earlier because the reference was wrong (whatever it was with the _root
variable).
stage.removeEventListener(Event.ENTER_FRAME, eFrame);
BUT - remember to do it before this part of your code:
while (_root.lvlHolder.numChildren > 0) {
_root.lvlHolder.removeChildAt(0);
}
because when the sprite is removed, it won't have the stage
property anymore. Just remember to clean up events in all possible scenarios. I'm not entirely sure stage
is the right place to place your enter frame event, I just assumed so because of what you earlier called _root.
Upvotes: 2
Reputation: 15338
you're adding eventListener to stage so try this:
stage.removeEventListener(Event.ENTER_FRAME, eFrame);
or
parent.removeEventListener(Event.ENTER_FRAME, eFrame);
or
event.target.removeEventListener(Event.ENTER_FRAME, eFrame);
Upvotes: 0
Reputation: 5577
Inside eFrame() stop the event listener:
removeEventListener(Event.ENTER_FRAME, eFrame);
Upvotes: 0