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

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.

Related

AS3 - Cannot access a property or method of a null object reference on gotoAndPlay

I have a scene that contains a movie clip. That movie clip has a button that controls the y position of a symbol in the scene. What I tried to do is move on to the next scene when the symbol reaches certain y values. I used gotoAndPlay when the desired y position was reached, the new scene was switched to but an error appeared on output as indicated by the title. This is the code that appears in the movie clip:
launch_btn.addEventListener(MouseEvent.CLICK, init_launch)
function init_launch(evt:MouseEvent):void
{
MovieClip(root).launch_video.play();
var k = setTimeout(launch, 1);
}
function launch():void
{
trace(MovieClip(root).rkt.y);
if(MovieClip(root).rkt.y != null)
{
//progressively changing the y position
if(MovieClip(root).rkt.y != null)
{
if(MovieClip(root).rkt.y < 600)
{
MovieClip(root).rkt.y -=0.3
}
if(MovieClip(root).rkt.y < 500)
{
...
}
setTimeout(launch, 1);
if(MovieClip(root).rkt.y < -150)
{
MovieClip(root).gotoAndPlay(1, "Scene 3")
}
}
}
Currently, as compile this code the error points to the line "trace(MovieClip(root).rkt.y);".
What I don't get is why rkt suddenly becomes null when I try to go to a different scene. I tried checking if the property is null but that doesn't help.
I tried removing eventListener, and calling functions that resided in the actions layer of the scene itself (the original one) instead of directly going to the scene from the movie clip.
All in vain.
Any ideas?
What I don't get is why rkt suddenly becomes null when I try to go to a different scene. I tried checking if the property is null but that doesn't help.
It's the object that's null, not the property.
I tried removing eventListener
Which won't help much given that the continuing calls to launch are not triggered by an event but setTimeout which will keep firing.
Stop using setTimeout and use a Timer. This allows you to remove the event listeners properly and actually stop it.
MovieClip(root) was actually the property that turned null when the y position was reached. I modified the condition inside launch() to handle that:
function launch():void
{
if(MovieClip(root)!= null)
{
rest of code...
}
}
I really hope this would help others. I only posted a question here after much research online and particularly here. It appears this error plagues a lot of developers.

External ActionScript Only Executed When Testing Single Scene

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!

AS3 gotoAndStop(2); causes a 1009 error second time the frame runs

Disclaimer: I'm really new/incredibly bad at AS3 so it's probably something really stupid that should never happen
Okay so, the first time my main menu frame runs, it runs fine and sends me to the gameplay frame when I press the button. After the gameplay is complete, it returns to the menu frame, and runs fine until I press the same button from before, which calls this error: .
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main_fla::MainTimeline/frame2()[Main_fla.MainTimeline::frame2:6]
at flash.display::MovieClip/gotoAndPlay()
at Main_fla::MainTimeline/easyPress()[Main_fla.MainTimeline::frame3:83]
at Main_fla::MainTimeline/mClickE()[Main_fla.MainTimeline::frame3:45]
My code for the button is as follows:
buttEasy.addEventListener(MouseEvent.CLICK, mClickE);
buttHard.addEventListener(MouseEvent.CLICK, mClickH);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mMove);
function mClickE(e:MouseEvent){
easyPress();
trace("easyP");
menuUsed = true;
}
function easyPress(){
trace("Waited for press and release");
sTime = 0;
sTempo = (6) ;
sBall = 0;
ballSpeed = 7;
gameIsOver = false;
menuUsed = true;
lvlArray0= new Array(1,0,0,2,0,0,1,0,0,3,0,0,1,0,0,2,0,0,1,0,0,3,0,01,0,0,2,0,0,1);
init2 = false;
buttEasy.removeEventListener(MouseEvent.CLICK, mClickE);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, mMove);
gotoAndPlay(2);
}
I honestly have no idea why this is happening. I'm using mouse events instead of button press events and whatnot because my movieclips started disappearing and flashing and other unexplainable stuff...
yeah...
I just registered, so I can't post this as a comment.
Anyway the error occurs on frame 2, not in the script you've provided (which is on frame 3).
You can see this in the error message:
"at Main_fla::MainTimeline/frame2()[Main_fla.MainTimeline::frame2:6]"
-> frame 2 line 6.
There you're accessing something that doesn't exist anymore. (-> something that is now null)
Maybe an object on the stage that has been removed. (But there are a lot of other possibilities, so don't stick with that solution)
Post the script you have on frame 3 for further help.
The flashing and other unexplainable stuff happens, because of this error. It aborts the script and runs the flash normally. (this means that for example the stop(); method won't be executed -> the player runs through all your frames -> the objects on the stage appear to be flashing)
You're probably just addressing the "stage" before the reference is given. Start your code with:
addEventListener(Event.ADDED_TO_STAGE, init);
and a handler for this listener
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// write your code after this
}
If you're framescripting (writing AS3 code in a frame) It's not really your problem.
But as the problem states - you're calling some objects property or method witch is null. Your debugger will be able to point to the null object that you try to call on frame 2.

Removing Children in AS3

My flash game exists of a timeline with multiple frames (I know I should avoid the timeline)
The point of the game is a point and click adventure. The object that you are able to pick up get spawned and destroyed accordingly as you enter and leave the room. now my problem is when entering frame 14 (accessibel from frame 12) it creates a piece of paper which you are able to pick up if you have another item. Now my problem is when you can't or don't pick up the paper and go back to frame 12 (only exit is to frame 12), you can't click on any other object and you are basicly stuck on frame 12. When leaving and entering other rooms it works properly but for some reason it doesn't for on the paper on frame 14.
My code to remove objects works as following
In my Main.as Documentclass I have a function that called as soon as the game starts which does the following
if (lastframe == 14)
{
trace (prop.numChildren);
while (prop.numChildren )
{
prop.removeChildAt(0);
}
}
The lastframe variable is established when moving from frames
this function is found on the frame itself (each exit function on it's own respective frame)
function exitKantine(event:MouseEvent):void
{
Main.lastframe = 14;
gotoAndStop(12);
}
The function to remove the prop actually removes it but then causes all other clickable objects to be unusable.
Thanks for looking at my question and thanks in advance for your suggestions
I would say instead of removing children, add it once in the beginning, add all the listeners in the beginning, and toggle the visibility instead of trying to addChild and removeChild every time you want to hide it. Use an array so you can have a few happening at the same time.
something like this:
private function init():void
{
assignVars();
addListeners();
stage.addChild // make sure this is in document class or you are passing stage to the class using it
}
for (var i = 0; i < _thingsAry.length; i++)
{
if (_thingsAry[i] == 14)
{
_thingsAry[i].visible = false;
trace("the visibility of _thingsAry[" + i + "] is " + _thingsAry[i].visible
}
}

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.