I am working on a Flash Tower Defense game. I have a main game loop which is an eventListener for each frame. Whenever you gain money or lose a life, I want the GameUI to be updated to display this change. Right now, it checks every frame for a change. How can I create an event to only change this information whenever the lives or money changes?
While Valke answered your question regarding custom events perfectly, I usually try to avoid Events in Flash for game-development. Robert Penner lists some good points why Events are bad.
Custom events are especially bad, when you're dispatching them very frequently (a common scenario in games), because every time you dispatch the event a new
With as3-signals, your game class could look something like this (I omitted any irrelevant stuff):
Your GameUI class would simply have a method to update the money:
All that is left to do, is to connect the signal to the update method (slot). You usually do this somewhere at initialization time, but you can also add/remove listeners/slots during runtime. eg.
Done! Whenever the game dispatches "moneyChanged", the gui will be updated.
This also works nicely with multiple listeners, so you could also have a
|show 3 more comments|
you can create a custom event class this way:
1 / In a new .as file (say GUIEvent.as) create the following class
2/ In the place you want to register for the events (probably your MainClass.as)
3/ Place the function provided to the addEventListener where it should be (still probably in your MainClass.as)
4/ Finally, dispatch the events when you need to update you GUI...
I do not practice AS3 anymore, but I have played with it for years so it should be almost OK... but I could have forgotten something through.