ActionScript 3.0 Type Was Not Found Or Was Not A Compile-Time Constant - actionscript-3

I just started programming a game and I when I ran my code it said
1064:Type Was Not Found Or Was Not A Compile-Time Constant:Event
1064:Type Was Not Found Or Was Not A Compile-Time Constant:Mouse Event
Here is the code:
package{
public class Script_1 {
public static const STATE_INIT:int = 10
public static const STATE_PLAY:int = 20
public static const STATE_GAME_OVER:int = 30
public var gameState:int = 0
public function gameLoop(e:Event):void{
switch(gameState) {
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_GAME_OVER:
gameOver();
break;
}
}
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
gameState = STATE_INIT;
}
stage.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
public function initGame():void{
stage.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
clicks = 0
gameState = STATE_PLAY;
}
public function playGame(){
if (clicks >= 10){
gameState = STATE_GAME_OVER;
}
}
public function onMouseClickEvent(e:MouseEvent):void{
clicks++;
trace("mouse click number:" + clicks);
}
public function gameOver():void{
stage.removeEventListener(MouseEvent.CLICK, onMouseClickEvent);
gameState = STATE_INIT;
trace("game over");
}
}
}
This is in a file called Script_1.as

You need to import those classes with the import statement. This statement is required for each class that is missing and belongs above the class definition:
package
{
// Imports.
import flash.events.Event;
import flash.events.MouseEvent;
public class Script_1
{
// ..
}
}
Also, some misc things I noticed:
You're using addEventListener() but Script_1 does not extend EventDispatcher or at least implement IEventDispatcher. Based on the events you're trying to listen for, Sprite seems most suitable.
It looks like your class should either be Game or your constructor function Game() should be Script_1().

Related

How do I get my movieclip character to move?

I've been trying for a few hours now and I cant get my little character to move with the keyboard.
I have ran a trace to make see if anything was happening and the position value does change but my character doesn't react to that position change.
I receive no errors. Both my Character and BrickBlock are movieclips and they have been imported for ActionScript.
If any other information is needed please let me know. Thank you! :)
My following code:
package {
import flash.events.Event
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class CharMove extends MovieClip {
var char1 :Character;
var block :BrickBlock;
public function CharMove()
{
char1 = new Character();
block = new BrickBlock();
//this.addEventListener(Event.ENTER_FRAME, collide)
stage.addEventListener(KeyboardEvent.KEY_DOWN, kDown);
}
/*function collide(e:Event):void
{
if(char.hitTestObject(block))
{
char.visible = !char.visible;
}
}*/
function kDown(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
char1.x -= 5;
trace(char1.x);
break;
case Keyboard.RIGHT:
char1.x +=5;
trace(char1.x);
break;
}
}
}
}
You might want to consider writing a static Input class.
package input {
import flash.display.Stage;
import flash.events.KeyboardEvent;
public class Input {
private static var keys:Array = new Array(255);
public static function setup(stage:Stage):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, KeyUp);
}
private static function keyDown(e:KeyboardEvent):void {
keys[e.keyCode] = true;
}
private static function keyUp(e:KeyboardEvent):void {
keys[e.keyCode] = false;
}
public static function isKeyDown(k:int):Boolean {
return keys[k];
}
public static const A:uint = 65;
public static const B:uint = 66;
public static const C:uint = 67;
// The rest of the keys...
}
}
To use it first call setup() which adds the listeners for KEY_DOWN and KEY_UP events.
They you can easily query keys and do relevant actions accordingly.
Input.setup(stage);
/...
if(Input.isKeyDown(Input.A)) {
char1.x -= 5;
}

AS3 - Referencing the Stage after Preloader Implementation

Ive just finished the basic structure of a little game and saved the simple preloader till last. Silly me.
After numerous tutorials I found this one that worked for me - Pre Loader in Flash Builder
The preloader works and the game is on the stage, but freezes instantly. Any reference to the stage in my LevelOne code throws up errors. error #1009: cannot access a property or method of a null object reference.
Before implementing the Preloader, my Application Class (RookiesGame) was used as a level switcher. Each level is contained in a Sprite. RookiesGame starts by adding LevelOne to stage, then once player completes it, RookiesGame removes LevelOne and adds LevelTwo to stage etc.
The level classes reference the stage with the _stage variable.
Since Ive been learning this structure, the preloader becoming the application class and RookiesGame becoming just another class has really confused me. Shouldn’t the _stage var still work? Is it okay to keep RookiesGame as a level switcher?
Anyway main problem is referencing the stage from the Level Classes.
Current code:
Preloader Class
Works fine, game starts.
package
{
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.utils.getDefinitionByName;
[SWF(width="650", height="450", backgroundColor="#FFFFFF", frameRate="60")]
public class Preloader extends Sprite
{
// Private
private var _preloaderBackground:Shape
private var _preloaderPercent:Shape;
private var _checkForCacheFlag:Boolean = true;
// Constants
private static const MAIN_CLASS_NAME:String = "RookiesGame";
public function Preloader()
{
trace("Preloader: Initialized.")
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function dispose():void
{
trace("Preloader: Disposing.")
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
if (_preloaderBackground)
{
removeChild(_preloaderBackground);
_preloaderBackground = null;
}
if (_preloaderPercent)
{
removeChild(_preloaderPercent);
_preloaderPercent = null;
}
}
// Private functions
private function onAddedToStage(e:Event):void
{
trace("Preloader: Added to stage.");
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP_LEFT;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e:Event):void
{
if (_checkForCacheFlag == true)
{
_checkForCacheFlag = false;
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: No need to load, all " + root.loaderInfo.bytesTotal + " bytes are cached.");
finishedLoading();
}
else
beginLoading();
}
else
{
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: Finished loading all " + root.loaderInfo.bytesTotal + " bytes.");
finishedLoading();
}
else
{
var percent:Number = root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal;
updateGraphic(percent);
trace("Preloader: " + (percent * 100) + " %");
}
}
}
private function beginLoading():void
{
// Might not be called if cached.
// ------------------------------
trace("Preloader: Beginning loading.")
_preloaderBackground = new Shape()
_preloaderBackground.graphics.beginFill(0x333333)
_preloaderBackground.graphics.lineStyle(2,0x000000)
_preloaderBackground.graphics.drawRect(0,0,200,20)
_preloaderBackground.graphics.endFill()
_preloaderPercent = new Shape()
_preloaderPercent.graphics.beginFill(0xFFFFFFF)
_preloaderPercent.graphics.drawRect(0,0,200,20)
_preloaderPercent.graphics.endFill()
addChild(_preloaderBackground)
addChild(_preloaderPercent)
_preloaderBackground.x = _preloaderBackground.y = 10
_preloaderPercent.x = _preloaderPercent.y = 10
_preloaderPercent.scaleX = 0
}
private function updateGraphic(percent:Number):void
{
// Might not be called if cached.
// ------------------------------
_preloaderPercent.scaleX = percent
}
private function finishedLoading():void
{
var RookiesGame:Class = getDefinitionByName(MAIN_CLASS_NAME) as Class;
if (RookiesGame == null)
throw new Error("Preloader: There is no class \"" + MAIN_CLASS_NAME + "\".");
var main:DisplayObject = new RookiesGame() as DisplayObject;
if (main == null)
throw new Error("Preloader: The class \"" + MAIN_CLASS_NAME + "\" is not a Sprite or MovieClip.");
addChild(main);
dispose();
}
}
}
RookiesGame Class (used to be application class)
Any references to the stage threw up #1009 error, which stopped when I changed stage.addChild to this.addChild
Ive not got to the level switch handler yet with the preloader, so I dont know how stage.focus will work either!
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
private function levelTwoSwitchHandler(event:Event):void
{
this.removeChild(_levelOne);
_levelOne = null;
this.addChild(_levelTwo);
stage.focus = stage;
}
}
}
LevelOne Class
Lots of #1009 errors. Anything referencing the stage.
Class is huge so I'll highlight problem chunks.
The #1009 error when referencing stage, adding the keyboard listeners.
_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Also #1009 when referencing stage to check stage Boundaries. Cant just change stage. to this. anymore.
private function checkStageBoundaries(gameObject:MovieClip):void
{
if (gameObject.x < 50)
{
gameObject.x = 50;
}
if (gameObject.y < 50)
{
gameObject.y = 50;
}
if (gameObject.x + gameObject.width > _stage.stageWidth - 50)
{
gameObject.x = _stage.stageWidth - gameObject.width - 50;
}
if (gameObject.y + gameObject.height > _stage.stageHeight - 50)
{
gameObject.y = _stage.stageHeight - gameObject.height - 50;
}
}
I reference _stage later in the program to remove the event listeners. Thats it.
_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
How can I reference the stage, without these errors and keep RookiesGame as the level switcher.
LevelOne Class Structure
To show how I use(d) _stage.
package
{
//import classes
public class LevelOne extends Sprite
{
//Declare the variables to hold the game objects
//A variable to store the reference to the stage from the application class
private var _stage:Object;
public function LevelOne(stage:Object)
{
_stage = stage;
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(event:Event):void
{
startGame();
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function startGame():void
{
//Includes _stage references that mess everything up.
}
private function levelCleared():void
{
//When Level finished, dispatch event to tell RookiesGame to switch levels.
dispatchEvent(new Event("levelOneComplete", true));
}
}
}
Sorry if thats confusing, but if you can help me reference the stage via LevelOne and RookiesGame classes, It would be much appreciated.
You are passing in a null stage to LevelOne from your RookiesGame class. Whenever you instantiate a RookiesGame the constructor will run first, it has not been added to the display list yet so its inherited reference to stage is null. What you need to do is add an event listener for ADDED_TO_STAGE in the RookiesGame class:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
addEventListener( Event.ADDED_TO_STAGE, onAdded );
}
//added to stage event
private function onAdded( e:Event ):void {
removeEventListener( Event.ADDED_TO_STAGE, onAdded );
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
...
}
Also if you are using addChild() call for LevelOne as in addChild(_levelOne) it has its own reference to stage after it's been added to the display list, you do not need to create a _stage variable for those classes if you are adding them to the display list.
Also you have the listener for ADDED_TO_STAGE in LevelOne, where the stage variable would have no longer been null, so you can remove your class variable _stage entirely.

Inherit MovieClip From Another Class

Hey I seem to be having some problems inheriting Movie-clip from a class, I'm fairly new to as3, I've had a look around and can't tell if I'm doing something fundamentally wrong or not.
Let me show you
So I have a class I want to use to move EVERYTHING but the player sprite. So I want everything but the player to extend it. (or so I'm assuming.)
So I declare my class
package code {
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import code.Main;
public class everythingContainer extends MovieClip {
function brackets and so on...
(I'm just importing everything in an attempt to avoid errors)
I then have a class I want to inherit everythingContainer and Movieclip
package code {
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import code.Main;
import code.everythingContainer;
public class Tree1 extends everythingContainer {
Yet when I run this I get the error:
Line 1 5000: The class 'code.Tree1' must subclass 'flash.display.MovieClip' since it is linked to a library symbol of that type.
Why am I getting this error?
Any help would be greatly appreciated!
I haven't got the full code to run yet so there may still be other obvious bugs laying about.
everythingContainer
Full code:
package code {
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import code.Main;
public class everythingContainer extends MovieClip {
var speed: Number = 4;
var wpressed: Boolean = false;
var apressed: Boolean = false;
var spressed: Boolean = false;
var dpressed: Boolean = false;
var xprev:int = 0;
var yprev:int = 0;
public function everythingContainer() {
// constructor code
trace ('Container started');
if(stage) init();
else
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
function init(eventInfo:Event = null):void
{
if(eventInfo != null)
{
this.removeEventListener(Event.ADDED_TO_STAGE, init);
trace ('Container init removed');
}
// constructor code
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyRelease);
this.addEventListener( Event.ENTER_FRAME, containerEveryFrame);
}
public function containerEveryFrame (Event): void {
if (stage.contains(Main.player)) {
xprev = this.x;
yprev = this.y;
checkPlayerMovement();
}
}
// check the set keypress variables
public function checkPlayerMovement () : void {
if (wpressed) {
this.y -= this.speed;
}
if (spressed) {
this.y += this.speed;
}
if (apressed){
this.x -= this.speed;
}
if (dpressed) {
this.x += this.speed;
}
}
//assign key presses to variables
public function onKeyPress (event:KeyboardEvent):void {
//up
if (event.keyCode == 87){
wpressed = true;
}
//down
if (event.keyCode == 83) {
spressed = true;
}
//left
if (event.keyCode == 65){
apressed = true;
}
//right
if (event.keyCode == 68) {
dpressed = true;
}
}
//reset key press variables
public function onKeyRelease (event:KeyboardEvent) : void {
//up
if (event.keyCode == 87){
wpressed = false;
}
//down
if (event.keyCode == 83) {
spressed = false;
}
//left
if (event.keyCode == 65){
apressed = false;
}
//right
if (event.keyCode == 68) {
dpressed = false;
}
}
}
}
Main (there's some other stuff going on in here, but at the minute I'm just trying to get the trees working with my other class.)
package code
{
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import flash.geom.Rectangle;
import flashx.textLayout.container.ContainerController;
public class Main extends MovieClip
{
//public static var main
public static var player:PC;
//public static var firstenemy: WolfEnemy;
public static var MainContainer:everythingContainer;
public function Main()
{
// constructor code
trace('main started');
if (stage)
{
init();
}
else
{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
function init(eventInfo:Event = null):void
{
if (eventInfo != null)
{
this.removeEventListener(Event.ADDED_TO_STAGE, init);
trace('Main init removed');
}
MainContainer = new everythingContainer ;
MainContainer.x = stage.stageWidth / 2;
MainContainer.y = stage.stageHeight / 2;
stage.addChild(MainContainer);
player = new PC();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
stage.addChild(player);
//firstenemy = new WolfEnemy();
//firstenemy.x = 100;
//firstenemy.y = 100;
//stage.addChild(firstenemy);
stage.addEventListener( Event.ENTER_FRAME, everyFrameMain);
}
// check if an enemy hits the player.
/*public function enemycollison(): void {
if(firstenemy.hitTestObject(player)){
trace ('hit enemy');
player.health--;
firstenemy.kill();
}
}*/
// manage events that need to haapen globally for every frame
public function everyFrameMain(Event):void
{
/*if (stage.contains(firstenemy)){
enemycollison();
} */
//root.scrollRect = new Rectangle(player.x - 400, player.y - 300, 800, 600);
}
// finish and close game
public function endgame():void
{
}
}
}
and finally my tree class
package code {
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import code.Main;
import code.everythingContainer;
public class Tree1 extends everythingContainer {
public function Tree1()
{
// constructor code
trace ('Tree1 started');
if(stage) init();
else
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
function init(eventInfo:Event = null):void
{
if(eventInfo != null)
{
this.removeEventListener(Event.ADDED_TO_STAGE, init);
trace ('Tree1 init removed');
}
this.addEventListener( Event.ENTER_FRAME, tree1EveryFrame);
}
public function tree1EveryFrame (Event): void {
playercollision();
}
public function playercollision(): void {
if(this.hitTestObject(Main.player)){
trace ('hit wall');
Main.player.x = Main.player.xprev;
Main.player.y = Main.player.yprev;
}
}
}
}
Probably due to linkage errors inside Fla-file.
RMB on library-item: Tree1
Export for ActionScript + Export in frame 1 + "class: code.Tree1"
File/Publish Settings/Actionscript Settings (the small wrench, right of Script-dropdown)
Source Path (add the linkage to where the compiler can find your package-folder), usually for me I crate a folder next to the fla file called src or something like that so the code-file would be found at "/MyProject/src/code/Tree1.as", in that case I add "./src/" inside Source path inside Advanced ActionScript 3.0 settings
Added an example project in Flash CS6 found at url:
https://user.iter.org/filesharing/?uid=927205f7-cdfe-4915-a175-bc87f64af444
that is available for ~40 days.
Project structure in that file:
"/MyProject/DeepInheritage.fla"
"/MyProject/src/code/Foobar.as"
"/MyProject/src/code/Tree1.as"
Foobar.as which extends MovieClip
Tree1 library item which extends Foobar
That should be the exact same thing that you described in your issue, meaning that there is nothing wrong with that approach, it is just a matter of finding what is wrong. Most likely that is due to errors inside FLA-file, but might be something else.
code files:
package code {
import flash.display.MovieClip;
public class Foobar extends MovieClip {
public function Foobar() {
trace("foobar ctor()");
}
}
}
package code {
import flash.display.MovieClip;
public class Tree1 extends Foobar {
public function Tree1() {
trace("Tree1 ctor()");
}
}
}

1119: Access of possibly undefined property monster through a reference with static type Enemy. AS3

Main.as
package{
import flash.display.MovieClip;
import flash.events.*;
public class Main extends MovieClip {
public var _root:MovieClip;
public var monsterContainer:MovieClip = new MovieClip();
public var delay = 30;
public function Main(){
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, enterFrameEvents);
}
function beginClass(e):void{
_root = MovieClip(root);
}
function enterFrameEvents(e):void{
addChild(monsterContainer);
delay -= 1;
if(delay <= 0){
var spawn:Slime = new Slime();
spawn.x = startPoint.x;
spawn.y = startPoint.y;
monsterContainer.addChild(spawn);
delay = 30;
}
}
}
Arrow.as
package{
import flash.display.MovieClip;
import flash.events.*;
public class Arrow extends MovieClip {
public var _root:MovieClip;
public var facingID;
public function Arrow(){
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, enterFrameEvents);
}
function beginClass(e):void{
_root = MovieClip(root);
}
function enterFrameEvents(e):void{
trace(_root.monsterContainer == null);
}
}
Enemy.as
package{
import flash.display.MovieClip;
import flash.events.*;
public class Enemy extends MovieClip {
public var _root:MovieClip;
//Status
public var monsterSpeed;
public var facing = "Right";
//CallingArrow
public var down:Down = new Down();
public function Enemy(){
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, enterFrameEvents);
}
function beginClass(e):void{
_root = MovieClip(root);
}
function enterFrameEvents(e):void{
//Facing Movement
if(_root.pausing == false){
if(facing == "Right"){
this.x += monsterSpeed;
}else if(facing == "Left"){
this.x -= monsterSpeed;
}else if(facing == "Down"){
this.y += monsterSpeed;
}else if(facing == "Up"){
this.y -= monsterSpeed;
}
}
}
}
Down.as
package {
import flash.display.MovieClip;
import flash.events.*;
public class Down extends Arrow {
public function Down(){
facingID = "Down";
}
}
Slime.as
package {
import flash.display.MovieClip;
import flash.events.*;
public class Slime extends Enemy {
public function Slime(){
monsterSpeed = 5;
}
}
and there is no additional code on timeline just stop();
I got 1119 error, when i want to access a movieClip inside slime, i give it monster for the instance name, please help !
Download Link : http://www.mediafire.com/download/hz5tptkgftwdipw/Tower_Defense.rar
It's only 15KB and using CS6 Please help !
Turn on Debugging
The code you're sharing is more than you probably need (.rar file included). To find the cause of the problem you (and those on StackOverflow) need to know what line you're programming is running into this error. If you're using Flash IDE CS6, the can be enabled by going to your publish settings and enabling "Permit Debugging". This will take your ambiguous error...
null object reference at myDocument/doSomething()
...to a much clearer...
null object reference at myDocument/doSomething() package\myClass.as:20
...which now denotes which line in your code to look for your issue.
Use the Debug Console
Use the debugging compile mode to bring up the Debug Console. This will provide you with an immediate look at the line of code in question, as well as the Call Stack, and the state of all available Variables. No programmer should be without it.
Enemy.monster
This is the crux of the issue: somewhere, you're calling on Enemy.monster, and there is no property on your Enemy class that's called that (method or otherwise).

AS3 - Having trouble with a basic game class

So I am creating a space shooter game. My document class is Engine and it looks like this:
package Classes
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
public class Engine extends MovieClip
{
private var startMenu:StartMenu;
private var numberOfStars:int = 80;
public static var enemyList:Array = new Array();
private var spaceShip:Ship;
private var hud:HUD;
public function Engine()
{
startMenu = new StartMenu();
stage.addChild(startMenu);
startMenu.x = (stage.stageWidth / 2);
startMenu.y = (stage.stageHeight / 2);
}
private function startGame()
{
stage.removeChild(startMenu)
spaceShip = new Ship(stage);
stage.addChild(spaceShip);
spaceShip.x = (stage.stageWidth / 2);
spaceShip.y = (stage.stageHeight / 2);
spaceShip.addEventListener("hit", shipHit);
hud = new HUD(stage); //create the HUD
stage.addChild(hud); //and display it.
for (var i:int = 0; i < numberOfStars; i++)
{
stage.addChildAt(new Star(stage), 1);
}
addEventListener(Event.ENTER_FRAME, createFighter);
}
}
So as you can see I am calling on another class called StartMenu. This is where I am having trouble: Here is the code (Or lack there of)
package Classes
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.*;
public class StartMenu extends MovieClip
{
public function StartMenu()
{
button1.addEventListener(MouseEvent.CLICK, buttonClicked);
}
private function buttonClicked(e:MouseEvent)
{
}
}
}
(Ignore the indentation errors, it is correct in the real code)
Okay so imagine a button being displayed on the screen. This button is part of the StartMenu Class and is listening for a MouseEvent.CLICK.
Once the button is clicked I need to somehow travel back to the Engine class and call the function startGame() , but I can't just do Engine.startGame() , I have tried setting the function to a public function, and I have tried setting the function to a public static function. no luck. HELP PLEASE?? Any method will be fine, I just need a way for this class to go to the startGame function once the button is clicked!
Probably the quickest way to do this is to add an Engine variable into the StartMenu class and pass the engine through the start menu's constructor. Here's a short code sample:
StartMenu
public class StartMenu extends MovieClip
{
private var _engine:Engine // add a new variable to the start menu class
public function StartMenu(engine:Engine) // add a new parameter to the constructor
{
_engine = engine; // set the variable to the value passed through the constructor
button1.addEventListener(MouseEvent.CLICK, buttonClicked);
}
private function buttonClicked(e:MouseEvent)
{
_engine.startGame()
}
}
Engine
public function Engine()
{
startMenu = new StartMenu(this);
// pass through the current instance of engine using the this keyword
...
}
public function startGame() // change private to public
{
...
}
I hope that helps
In your Engine.as class, you can put :
public static var instance:Engine;
public static function getInstance():Engine
{
return instance as Engine;
}
and in constructor of engine class put :
instance = this;
now you can use instace of Engine class and all the public functions and variables anywhere in your project by :
Engine.getInstance().startGame();
It can help you.
There are two types of solving such a case. One is using parent reference or specific reference to call a certain function, as Ethan Worley andwered, the other is using a customizable public clicker setter like this:
public class StartMenu extends MovieClip
{
private var button1:MovieClip; // or whatever type your button is
private var startGameFunction:Function;
public function StartMenu()
{
// some initialization code if needed, including allocating button1
startGameFunction=null;
button1.addEventListener(MouseEvent.CLICK, buttonClicked);
}
public function set startGameClicked(value:Function):void {
if (value==startGameFunction) return; // nothing to set
startGameFunction=value;
}
private function buttonClicked(e:MouseEvent)
{
if (startGameFunction) startGameFunction(); // if there's a function assigned, call it
}
}
Engine class:
public function Engine()
{
startMenu = new StartMenu();
startMenu.startGameFunction=this.startGame;
// no "()" here, as we are giving a function reference
...
}
public function startGame() // change private to public
{
...
}
I am a bit surprised that no one mentioned an Events based approach yet. That's what I would have used for such a requirement, since I don't really find the idea of passing an entire class instance for just a function call to be that appealing (that would mean that I may be a bit biased towards this approach so please feel free to point out the drawbacks it has, if any).
Inside your Engine class:
public function Engine()
{
startMenu = new StartMenu();
startMenu.addEventListner('StartGame', startGame);
stage.addChild(startMenu);
..
}
private function startGame(e:Event)
{
startMenu.removeEventListner('StartGame', startGame);
..
}
Inside your StartMenu class:
private function buttonClicked(e:MouseEvent)
{
this.dispatchEvent(new Event('StartGame'));
..
}