External ActionScript Only Executed When Testing Single Scene - actionscript-3

New to AS 3.0 and I seem to have an issue where an external AS file is run when I test an individual scene in Flash Pro but not when I test the entire movie or when I test from Flash Builder. Anyone know what the problem might be?
Here's the code from the AS file:
package {
import flash.display.MovieClip;
public class Level1 extends MovieClip {
public var myplayer:MyPlayer;
public function Level1() {
super();
myplayer.x = 516;
myplayer.y = 371;
if (myplayer.x == 516)
{
trace("player x is 516");
}
else if (myplayer.y == 371)
{
trace("player y is 371");
}
}
}
}
Any ideas?
EDIT
I think I figured out the problem. The swf contained two scenes, and the external AS file started running at the start of Scene 1, but the myPlayer movie clip was not instantiated until Scene2, which, I think was causing the problem I was having, in addition to giving a 1009 null object error.
So I simply deleted the first scene, and now everything works fine. Maybe I will put that first scene in a separate SWF? Or, is there some way to delay a script's execution until a certain scene?

Your problem:
When the constructor of your doucment class runs, myPlayer doesn't yet exist so it throws a 1009 runtime error and exits the constructor at the first reference to myPlayer.
Solutions:
Put all the myPlayer code on the first frame of the MyPlayer timeline. OR use your current document class as the class file for MyPlayer (instead of documentClass). Change all references to myPlayer to this.
Listen for frame changes and check until myPlayer is populated, then run your code.
this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
function enterFrameHandler(e):void {
if(myPlayer){
//run the myPlayer code
this.removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
}
}
If your frame rate is 24fps, this code though will run 24 times every second (until it finds myPlayer), so it's not the most performant way to go.
Use events. Add an event to the first frame of myPlayer (or to a class file for MyPLayer) that tells the document class that it exists now.
stage.dispatchEvent(new Event("myPlayerReady"));
Then listen for that event on the document class:
stage.addEventListener("myPlayerReady",playerReadyHandler);
playerReadyHandler(e:Event):void {
//your player code
var myPlayer = MyPlayer(e.target); //you can even get the reference from the event object
}

Thanks for your constructive, helpful responses, LDMS. I thought I had found a solution when I hadn't. Your advice worked. What I did was add the following code to the timeline of MyPlayer
this.x = 516;
this.y = 371;
if (this.x == 516)
{
trace("player x is 516");
}
if (this.y == 371)
{
trace("player y is 371");
}
and I removed the code from the document class. Everything seems to be working fine now. Thanks again for your help!

Related

SImple Coloring Book: Error #1009: Cannot access a property or method of a null object reference

I am creating a simple flash coloring book and am not very familiar with as3 programming language.
I entered the following code,and when I attempted to press the back button in the test movie I got that error.
stop();
back_btn.addEventListener(MouseEvent.CLICK, GoToChooseA);
function GoToChooseA(event:MouseEvent):void
{
gotoAndStop("Choose");
}
color_scroll.mask = myMask;
var goY: Number = color_scroll.y;
stage.addEventListener(Event.ENTER_FRAME, scrollManage);
function scrollManage(Event): void {
color_scroll.y += (goY - color_scroll.y) / 20;
}
up_btn.addEventListener(MouseEvent.MOUSE_DOWN, scrollUP);
down_btn.addEventListener(MouseEvent.MOUSE_DOWN, scrollDown);
function scrollUP(MouseEvent): void {
goY += 20;
}
function scrollDown(MouseEvent): void {
goY -= 20;
}
*
It seems to indicate the error is here
color_scroll.y += (goY - color_scroll.y) / 20;
But I'm really bummed because I'm not really sure how to proceed from there.
Whenever you gotoAndStop() to a different keyframe, your current frame is invalidated and all its members destroyed. Listeners persist, if they are attached to an object that persists. So, right after you call GoToChooseA(), your color_scroll is destroyed, and then the listener attached to stage is called and tries to modify a destroyed object, there goes your 1009. The solution is either manually remove the event listeners "scrollManage", "scrollUp", "scrollDown" before you change the frame, at least "scrollManage" because it's attached to stage, or stop using frames altogether, but even then you'll have to control your event listeners.
You could add some logic to your function to check if you are in the right frame and then proceed. I am not familiar with frames so the condition would be something like this._currentframe == 2 or timeline.currentFrame == 2.
function scrollManage(Event): void {
if ( condition ) {
color_scroll.y += (goY - color_scroll.y) / 20;
}
}
If you are not at the right frame (in my example that is frame 2), the function does not execute any code.
This error means you are trying to modify something that is no longer existent.

method (function) in subClass not being called on mouse event

My goal is:
define a subClass of Sprite called Ship
use an event at runtime to call a function within this new class
It seems that I've figured out how to create my Ship class using a package in a linked .as file. But I can't seem to access the function within that class. Can anyone see what I'm doing wrong?
var ShipMc:Ship = new Ship();
addChild(ShipMc);// This successfully adds an instance, so I know the class is working.
addEventListener(MouseEvent.CLICK, ShipMc.addShip);//But this doesn't seem to run the function
This code works fine for instantiating a Sprite, but the code in the Ship.as file, specifically the function, is not working. No runtime errors, but nothing traced to the output window, either.
package
{
import flash.display.Sprite
public class Ship extends Sprite
{
public function addShip():void
{
trace("running addShip function")
}
}
}
The last time a coded anything in flash it was AS2!
I'll just mention that I've tried using addShip():void and just addShip(). Same response with both. It should be with :void, right? Anyway, the fact that neither one throws, tells me that this section of code isn't even getting read, I think.
Any help is much appreciated! Pulling my hair out.
Your code is not working because it contains some problems, so let's see that.
You should know that you are attaching the MouseEvent.CLICK event listener to the main timeline which didn't contain any clickable object yet now (it's empty), so let's start by adding something to your Ship class to avoid that :
public class Ship extends Sprite
{
// the constructor of your class, called when you instantiate this class
public function Ship()
{
// this code will draw an orange square 100*100px at (0, 0)
graphics.beginFill(0xff9900);
graphics.drawRect(0, 0, 100, 100);
graphics.endFill();
}
public function addShip():void
{
trace("addShip function run");
}
}
N.B: You can attach the MouseEvent.CLICK event listener to the stage, which will work even if you have nothing in the stage.
Now, if you test your app, you'll get an clickable orange square at the top left corner of your stage, but the compiler will fire an error (ArgumentError) because it's waiting for a listener function (the Ship.addShip() function here) which accept an MouseEvent object.
So to avoid that error, your Ship.addShip() function can be like this for example :
public function addShip(e:MouseEvent):void
{
trace("addShip function run");
}
Then your code should work.
You can also simplify things by using another listener function in your main code which can call the Ship.addShip() function, like this for example :
var ShipMc:Ship = new Ship();
addChild(ShipMc);
addEventListener(MouseEvent.CLICK, onMouseClick);
function onMouseClick(e:MouseEvent): void
{
ShipMc.addShip();
}
For more about all that, you can take a look on AS3 fundamentals where you can find all what you need to know about AS3.
Hope that can help.

Why is my button instance forgetting its textfield text and event listener?

I'm working on an assignment due at midnight tomorrow and I'm about to rip my hair out. I am fairly new to ActionScript and Flash Builder so this might be an easy problem to solve. I think I know what it is but I do not know for sure...
I'm developing a weather application. I designed the GUI in Flash CS5. The interface has 2 frames. The first frame is the menu which has a zipcode input and a button instance called "submit". On the second frame, it has another button instance called "change" which takes you back to the first frame, menu.
In Flash Builder 4, I wrote a class to extend that GUI called Application. When Main.as instantiates it, the constructor function runs. However, this was my first problem.
public class Application extends InputBase {
public function Application() {
super();
// Y U NO WORK???
this.gotoAndStop(1);
this.change.tfLabel.text = "Change";
}
}
When I ran debug it tossed a #1009 error saying it could not access the property or method of undefined object. It is defined on frame 2 in Flash CS5. I think this is the problem... Isn't ActionScript a frame based programming language? Like, you cannot access code from frame 2 on frame 1? But, I'm confused by this because I'm not coding on the timeline?
Anyway, I thought of a solution. It kinda works but its ugly.
public class Application extends InputBase {
public function Application() {
super();
// Y U NO WORK???
this.gotoAndStop(1); // when app is first ran, it will stop on the first frame which is the menu frame
setButton(this.submit, "Submit", 1);
setInput(this.tfZipCode);
}
private function submitZip(e:MouseEvent):void {
this.nextFrame();
setButton(this.change, "Change", 2);
}
private function menu(e:MouseEvent):void {
this.prevFrame();
setButton(this.submit, "Submit", 1); // if I comment this out, the submit button will return to the default text label and it forgets it event.
}
private function setButton(button:ButtonBase, string:String="", action:uint=0):void {
button.buttonMode = true;
button.mouseChildren = false;
button.tfLabel.selectable = false;
button.tfLabel.text = string;
switch (action) {
case 1:
button.addEventListener(MouseEvent.CLICK, submitZip);
break;
case 2:
button.addEventListener(MouseEvent.CLICK, menu);
break;
default:
trace("Action code was invalid or not specified.");
}
}
}
Its not my cup of tea to run the set button function every time one of the button instances are clicked. Is this caused by frames or something else I maybe looking over?
I believe you have two keyframes & both have an instance of the button component called button.
If you are working on the timeline try putting the button in a separate layer, with only one key frame.
Something like the following:
Ensures that you are referencing the same button every time & not spawning new ones on each frame.

ENTER FRAME stops working without error

When does ENTER_FRAME stops?
1. removeEventListener(Event.ENTER_FRAME,abc);
2. error occurs or the flash crashes
3. the instance of class is removed from stage
4. ?
The story:
I have several AS document for a game,one of it contains ENTER_FRAME which adding enemies.
It works fine usually,but sometimes it don't summon enemies anymore. I didn't change anything,I have just pressed Ctrl+enter to test again.
I have used trace to check, and found the ENTER_FRAME stops.
Otherwise, I put trace into another AS file of ENTER_FRAME, it keeps running.
Another ENTER_FRAME in levelmanage class for testing if it's working, both of it and addEventListener(Event.ENTER_FRAME, process); stops too
I also don't get any errors, and I can still move my object via keys.
The levelmange class doesn't connect to any object,it shouldn't stop if anything on stage has removed.
what could be the problem?
The below as code is the one who stops operating.
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.*;
public class levelmanage extends MovieClip
{
var testing:int=0
private var sttage = ninelifes.main;
public var framerate = ninelifes.main.stage.frameRate;
public var levelprocess:Number = 0;
public var levelprocesss:Number = 0;
private var level:int;
public var randomn:Number;
public function levelmanage(levell:int)
{
level = levell;
addEventListener(Event.ENTER_FRAME, process);
}
function process(e:Event)
{
testing+=1
if(testing>200){
testing=0
trace("working")//it don't trace "working"sometimes which means enterframe doesn't going
}
if (levelprocess>levelprocesss)trace(levelprocess);
levelprocesss = levelprocess;
if (levelprocess>=100 && enemy.enemylist.length==0)
{
finish();
return();
}
if (levelprocess<=100 && enemy.enemylist.length<6)
{
switch (level)
{
case 1 :
arrange("cir",0.5);
arrange("oblong",1);
break;
}
}
}
public function arrange(enemyname:String,frequency:Number)
{
randomn = Math.random();
if (randomn<1/frequency/framerate)
{
var theclass:Class = Class(getDefinitionByName(enemyname));
var abcd:*=new theclass();
sttage.addChild(abcd);
trace("enemyadded")
switch (enemyname)
{
case "cir" :
levelprocess += 5;
break;
case "oblong" :
levelprocess += 8;
break;
}
}
}
private function finish()
{
levelprocess=0
trace("finish!");
removeEventListener(Event.ENTER_FRAME,process);//not this one's fault,"finish" does not appear.
sttage.restart();
}
}
}
It's possible you eventually hit "levelprocess==100" and "enemy.enemylist.length==0" condition, which causes your level to both finish and have a chance to spawn more enemies, which is apparently an abnormal condition. It's possible that this is the cause of your error, although unlucky. A quick fix of that will be inserting a "return;" right after calling finish(). It's also possible that your "levelmanage" object gets removed from stage somehow, and stops receiving enter frame events, which might get triggered by a single object throwing two "sttage.restart()" calls. Check if this condition is true at any time in your "process" function, and check correlation with this behavior. And by all means eliminate possible occurrence of such a condition.
if(testing>200){
testing=0
trace("working")//it don't trace "working"sometimes which means enterframe doesn't going
}
The deduction in your comment isn't correct. It means either EnterFrame isn't firing, or testing <= 200.
Try putting a trace right at the beginning of your process function.
If you don't have removeEventListener elsewhere, then it is unlikely EnterFrame is really stopping - it's hard to be sure from the example you've posted but I would bet the problem is somewhere in your logic, not an issue with the EnterFrame event itself.

Flash CS5.5 Output Error

I have been creating a hypermedia player, and i have got to a stage where it is glitching out and it is apparently a...
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at AvalancheCityHypermediaPlayer_fla::MainTimeline/fl_CustomMouseCursor()
Here is my code:
import flash.events.Event;
cust_cursor.mouseEnabled= false;
cust_cursor.addEventListener(Event.ENTER_FRAME, fl_CustomMouseCursor);
function fl_CustomMouseCursor(event:Event)
{
cust_cursor.x = stage.mouseX;
cust_cursor.y = stage.mouseY;
}
Mouse.hide();
I am not sure why it is not working properly, basically when a button is hovered over it is meant to jump to frame 2 and stop, but it is jumping to that frame, and then jumping straight to frame 1 without stopping on frame 2, and stops on frame 1.
1 . Your error isn't producing a line number. You (and I) will find this invaluable for debugging; if in the Flash IDE, you can turn this on in the Publish Settings under swf preferences as a toggle titled "Permit debugging".
2 . Is this code inside a class, or in document code (e.g., Flash IDE "Actions" tab)? If it's inside a class, make sure you pass a reference of the stage to the constructor of your class and assign it to an internally persistent variable so that fl_CustomMouseCursor can address it. By default, classes have no internal way of referencing the stage, and I'm assuming that's what's producing your #1009 error.
For example, inside your class constructor...
package com.example {
public class MyClass {
private var stage;
public function MyClass(arg) {
stage = arg;
}
}
}
And outside when instantiating the class...
var myObj:MyClass = new MyClass(stage);
3 . If you want your code to stop on a frame, use stop(); or gotoAndStop()
4 . Finally, if you're compiling with Flash IDE, you can debug this and see exactly which variable in the stack the runtime environment is having issues with. You can access it from the debug menu or by compiling with control-shift-enter.