Using MovieClip(root) in ActionScript 3 - actionscript-3

im at frame 3.. i have text field on the stage name scoreTxt.. at frame 3 i added TryClass..
var Try:TryClass = new TryClass();
TryClass has function of updateScore.. this is working fine if im on frame 3. so my code is
public function updateScore(amount:int):void
{
score += amount;
if(score < 0) score = 0;
realNumber = score;
setInterval(updateDisplayedScore, 10);
}
public function updateDisplayedScore():void
{
displayedNumber += Math.round((realNumber-displayedNumber)/5);
if (realNumber - displayedNumber < 5 && realNumber - displayedNumber > -5)
{
displayedNumber = realNumber;
}
addZeros();
}
public function addZeros():void
{
var str:String = displayedNumber.toString();
MovieClip(root).scoreNa.text = str;
}
but then if for example .. the user died or he reaches the required score.. im suppose to go a certain frame using this code..
MovieClip(this.root).gotoAndStop("Main"); this code is on the class..
its reaching the frame "Main" but its pointing errors to this -->
MovieClip(root).scoreTxt.text
that "Main" frame is on frame 4.. which i did not yet added the TryClass.. should i add to all my frames the TryClass? and how is that?
Sorry for the question.. i dont know yet how to perfectly code in the class.. and accessing the timelines and other external class.. Please dont use deeper language of actionscript.. on a beginner way only..
here is the full error message when i go to the frame "Main"
TypeError: Error #1009: Cannot access a property or method of a null object reference.
atTumba/addZeros()[C:\Documents and Settings\Chrissan\Desktop\Game and Docs\Game\Tumba.as:686]
atTumba/updateDisplayedScore()[C:\Documents and Settings\Chrissan\Desktop\Game and Docs\Game\Tumba.as:680]
atFunction/http://adobe.com/AS3/2006/builtin::apply()
atSetIntervalTimer/onTimer()
atflash.utils::Timer/_timerDispatch()
atflash.utils::Timer/tick()
this is the line 686 of Tumba.as - MovieClip(root).scoreNa.text = str;
public function updateDisplayedScore():void
{
displayedNumber += Math.round((realNumber-displayedNumber)/5);
if (realNumber - displayedNumber < 5 && realNumber - displayedNumber > -5)
{
displayedNumber = realNumber;
}
addZeros(); -->> this is the line 680 of Tumba.as
}
about the setInterval sir.. its working fine cause i imported the flash.utils.* ..its working fine on frame 3 which i added the class.. but on "Main" fram. it isnt..

Try using (root as MovieClip) instead of MovieClip(root)

My guess would be that "root" is undefined, because I'm guessing TryClass is not inherited from a MovieClip or other DisplayObject that lives in the existing heirarchy.
To fix it, I'd add a parameter to the class's constructor. Then, I would send it a movieclip that you can access. For instance, if you are instantiating your class from within a movieclip, just send it the "this" for that movie.
public class TryClass {
...
static var myroot:MovieClip = null;
...
public function TryClass(someclip:MovieClip=null) {
...
if (this.myroot == null && someclip != null && someclip.root != undefined) {
this.myroot = someclip.root;
}
...
}
...
}
Then from within a movie clip:
var something = new TryClass(this);
Anyway, this is the technique I'm using for a class that I'm making. For mine, I have it adding an instance of an external movie clip if the class detects that the root does not already have it loaded. In my case, a universal loading-bar called from my loading wrapper class. If a particular movie I put it in already has a custom loading bar, then it won't do anything, but for any I don't have one in yet, it'll add it.

Related

AS3 MOVING OBJECT ON SPECIFIC FRAME

so i've been working on this game for a week now and i dont have any coding background at all so im trying to find tutorial here and there.. then i come up with this problem ...
so what i wanna do is move the object (CHARA) to the right when i hit frame 80 inside (CHARA,which is a nested movieClip with 99 frames btw ) then move it back to original position when i hit frame 99...
the problem is anything i do doesn't make my object move at all (movieClip still played btw) what did i do wrong here? did i just put the code at the wrong position ?? (CHAR is moved only if i put the code x= directly inside frame 80 but i try using class here)
here is my code,sorry i know its messy its my first code i try my best here
package {
public class Main extends MovieClip {
public var CHARA:CHAR = new CHAR;//my main char
public var rasen:Rasen_button = new Rasen_button;//the skill button
public var NPCS:NPC = new NPC;// the npc
public function Main() {
var ally:Array = [265,296];//where me and my ally should be
var jutsu:Array = [330,180];// where the buttons should be
var enemy:Array = [450,294];//where the enemies should be
addChild(NPCS);
NPCS.x = enemy[0];
NPCS.y = enemy[1];
NPCS.scaleX *= -1;
addChild(rasen);
rasen.x = jutsu[1];
rasen.y = jutsu[0];
addChild(CHARA);
CHARA.x = ally[0];
CHARA.y = ally[1];
rasen.addEventListener(MouseEvent.CLICK, f2_MouseOverHandler);
function f2_MouseOverHandler(event:MouseEvent):void {
CHARA.gotoAndPlay(46); //here is the problem
if (CHARA.frame == 80)
{
CHARA.x = ally[1]; //just random possition for now
}
}
}
}
}
any suggestions?
Your if statement is inside a click handler (f2_MouseOverHandler), so it only gets executed when a user clicks rasen, not necessarily when the playback reaches frame 80. This is a common beginner mistake related to timing and code execution. The most straight forward solution is to write some code that will execute every frame using an ENTER_FRAME handler:
rasen.addEventListener(MouseEvent.CLICK, f2_MouseOverHandler);
function f2_MouseOverHandler(event:MouseEvent):void {
CHARA.gotoAndPlay(46); //here is the problem
// add an ENTER_FRAME handler to check every frame
CHARA.addEventListener(Event.ENTER_FRAME, chara_EnterFrameHandler)
}
function chara_EnterFrameHandler(event:Event):void {
if (CHARA.currentFrame == 80)
{
CHARA.x = ally[1]; //just random possition for now
// remove the ENTER_FRAME after the condition is met
// so it stops executing each frame
CHARA.removeEventListener(Event.ENTER_FRAME, chara_EnterFrameHandler);
}
}

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.

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!

ActionScript 3 - use [brackets] instead of getChildByName

I have a MovieClip inside library, linkaged to MyObject and it contains a textField.
I don't know how I can access this textField without using the getChildByName method.
Apparently, the 3rd section works when object is on stage (without using addChild). But when using addChild I think there has to be some kind of casting; which I don't know how.
var childElement: MyObject = new MyObject();
childElement.name = "theChildElement";
container.addChild(childElement);
btn.addEventListener(MouseEvent.CLICK, changeText);
function changeText(event: MouseEvent): void
{
var targetBox:MovieClip = container.getChildByName(childElement.name) as MovieClip;
targetBox.textField.text = "hello"; // THIS WORKS
// This works too:
// MovieClip(container.getChildByName("theChildElement"))["textField"].text = "hello"; // THIS WORKS TOO.
// THIS DOESN'T WORK. why?
// container["theChildElement"]["textField"].text = "hello";
}
As confusing as it may seem, instance name, and name are not the same. From your code you should always be able to get to your MC by it's variable name. To get your last like to work you could just use this.
childElement["textField"].text = "hello";
There is a difference between Symbols created by the Flash IDE, which aggregate other DisplayObjects and programmatically created DisplayObjects.
When a DisplayObject is created in the Flash IDE, it's instance name can be used to resolve the instance as a property - which means it can be accessed via []. The [] can be used to access properties or keys of dynamic declared classes - like MovieClip. This necessary because you'll most likely down cast to MovieClip instead of using the symbol class created by Flash. That is not possible when simply using addChild, addChildAt or setChildAt from the DisplayObjectContainer API.
It is always the save way to access it via getChildByNameand check for null because otherwise your app, website or whatever is doomed for 1009 errors as soon as someone is changing the symbols.
I'd create a bunch of helper methods, like
// not tested
function getChildIn(parent:DisplayObjectContainer, names:Array):DisplayObject {
var child:DisplayObject, name:String;
while (names.length > 0) {
name = names.shift();
child = parent.getChildByName(name);
if (!child) {
// log it
return null;
}
if (names.length == 0) {
return child;
}
}
// log it
return null;
}
function getTextFieldIn(parent:DisplayObjectContainer, names:Array):TextField {
return getChildIn(parent, names) as TextField;
}
function getMovieClipIn(parent:DisplayObjectContainer, names:Array):MovieClip {
return getChildIn(parent, names) as MovieClip;
}
Your third method doesn't work because you are trying to call the ChildElement by it's name
without using getChildByName method. On the other hand, you shouldn't call your textField textField, because that's already an actionScript property.
Your should rather call it 'displayText' for example.
For a textField called 'displayText' contained in childElement :
function changeText(event:MouseEvent): void
{
childElement.displayText.text = "hello";
}

MovieClip(root) line seems to be crashing my game

Inside my classes, I invoke this function
MovieClip(root).increaseScore();
which handles the score in the main .as file.
It all works fine during the execution of the level. However when the level is finished and the screen goes to another frame, the game crashes and gives me this error
TypeError: Error #1009: Cannot access a property or method of a null
object reference.
on the line above.
How do I fix this?
Thanks
edit:
This is were I tell it to addScore, this is in the GameController.as file
private function removeBubble(bubble, addScore:Boolean)
{
var delay:Timer = new Timer(200, 1);
delay.addEventListener(TimerEvent.TIMER_COMPLETE, function(e:TimerEvent)
{
if(bubble.parent==mcGameStage)
{
var j:int = bubbleList.indexOf(bubble);
bubbleList.splice(j,1);
if(addScore) bubble.addScore();
mcGameUI.txtScorePlayer.text = String(playerScore);
mcGameStage.removeChild(bubble);
}
e.currentTarget.removeEventListener(e.type, arguments.callee);
checkWin();
});
delay.start();
}
here is the checkWin function:
private function checkWin()
{
if (playerBlue + playerRed + playerYellow + playerOrange + playerPurple + playerGreen == 0)
{
gameWin();
}
}
private function gameWin()
{
while (bubbleList.numChildren > 0)
{
bubbleList.removeChildAt(0);
}
mcGameUI.btnMixBlue.removeEventListener(MouseEvent.CLICK, mixBlue);
mcGameUI.btnMixRed.removeEventListener(MouseEvent.CLICK, mixRed);
mcGameUI.btnMixYellow.removeEventListener(MouseEvent.CLICK, mixYellow);
mcGameUI.btnNeedle.removeEventListener(MouseEvent.CLICK, activateNeedle);
mcGameStage.removeEventListener(Event.ENTER_FRAME,update);
mcGameStage.removeEventListener(MouseEvent.CLICK, checkToHit);
removeEventListener(Event.ADDED_TO_STAGE, gameAddedToStage );
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
if (mouseCursor != null)
{
mouseCursor.removeEventListener(Event.ENTER_FRAME,followMouse);
mouseCursor = null;
}
gotoAndPlay("level1win");
}
And inside my classes,
public function addScore()
{
root["increaseScore"]();
}
This is what increaseScore does
public function increaseScore()
{
playerScore += 1000;
}
So where is the null object? D:
Also I am very inexperienced using the debugger so I apologize if this could be easily solved with that. I tried it and couldn't figure it out before coming here.
What is OPP method?
What is FrameScript?
Also, the class is MovieClip
thanks :)
Fixing this is done with the help of the debugger!
The error is telling you that something is null and you're trying to access it. That's not good, so let's think what could be null?
1) Your movie clip instance might be null.
2) increaseScore() method of your movie clip instance might try to access something that is null
You didn't post any code that I could analyse at the time I'm writing this answer, so I can't say for sure.
Some possible problems:
Your class is not called MovieClip, but you're just trying to cast your root object to a MovieClip. Thing is, MovieClip's don't have a increaseScore() method. You should instead call the increaseScore() method with
root["increaseScore"]();
This will call the method of your root timeline, but since we are using weak-typing, you might have problems with debugging it later. But I guess that's the price you pay when writing all the code in a frame instead of using OPP approach.
The true reason here is said in the error: Cannot access a property or method of a null object reference.
What this means is that MovieClip(root) is null (it doesn't even bother to check if the function is present). The reasons for this might be three:
Your document class is not MovieClip (could be Sprite).
The class you use root in, is not DisplayObject. The property is part of the DislpayObject class and so if you use it on other kind of classes that does not extend it, it won't work.
You are using this piece of code before you have added the instance to the stage (most probable cause). The root property represents the top-most display object in the tree. If you haven't added the child to the tree, it has no roots :) Check out parent - the error should be the same.