Step 7. Lag
Adding this many eventListener will eventually cause the game to lag. Fortunately, there is a way to remove them once they are no longer needed.
this.arrowHallway1.removeEventListener(Event.ENTER_FRAME, hoverarrowHallway1);
Yes, it's as simple as that.
You should be removing all the Event listeners when you leave a room; they will be added back once you re-enter the room. Let's go back to the first room’s code.
this.arrowHallway1.addEventListener(MouseEvent.CLICK, enterHallway1); function enterHallway1(event:MouseEvent):void { Object(root).game.gotoAndStop(“hallway1”); } this.arrowHallway1.addEventListener(Event.ENTER_FRAME, hoverarrowHallway1); function hoverarrowHallway1(event:Event):void { if (this.arrowHallway1.hitTestPoint(stage.mouseX, stage.mouseY, true) { this.arrowHallway1.nextFrame(); } else { this.arrowHallway1.prevFrame(); } } this.cheezmc.addEventListener(MouseEvent.CLICK, cheezget); function cheezget(event: MouseEvent): void { this.cheezmc.visible = false; Object(root).Inv.Itembox1.gotoAndStop(“cheez); Object(root).Inv.Itembox1.Itemboxflash.gotoAndPlay(1); }
We need it so that when we leave the room, all the other event listeners are deleted. You could do this:
this.arrowHallway1.addEventListener(MouseEvent.CLICK, enterHallway1); function enterHallway1(event:MouseEvent):void { this.arrowHallway1.removeEventListener(MouseEvent.CLICK, enterHallway1); this.arrowHallway1.removeEventListener(Event.ENTER_FRAME, hoverarrowHallway1); this.cheezmc.removeEventListener(MouseEvent.CLICK, cheezget); Object(root).game.gotoAndStop(“hallway1”); }
But once you have 20 or so items, that eats up a lot of lines. Instead, try putting them all into a function.
this.arrowHallway1.addEventListener(MouseEvent.CLICK, enterHallway1); function enterHallway1(event:MouseEvent):void { removeAll(); Object(root).game.gotoAndStop(“hallway1”); } function removeAll() { // you can call the function whatever you want this.arrowHallway1.removeEventListener(MouseEvent.CLICK, enterHallway1); this.arrowHallway1.removeEventListener(Event.ENTER_FRAME, hoverarrowHallway1); this.cheezmc.removeEventListener(MouseEvent.CLICK, cheezget); }
If you are familiar with Scratch, these are like custom blocks. This way, anytime you add a new item that can be interacted with, you can add the code to remove it only once into the function. Make sure to place the removeAll(); BEFORE you move to the next room, or else it won’t work.