AS3 Error accessing parent methods and variables - actionscript-3

I'm learning AS3 and I understand that there are a bunch of related questions here with this type of error but I can't seem to figure it out.
I'm getting this error:
TypeError: Error #1034: Type coercion failed: cannot convert bej_cs5_fla::MainTimeline#330ae041 in Board.
at BoardTimer/gameOver()
at BoardTimer/countdown()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
I have to classes. Class Board and class BoardTimer.
Board:
public class Board extends MovieClip {
//Attributes
public var boardSide:uint;
public function Board(dimention:uint) {
boardSide = dimention;
// Code goes here
}
}
BoardTimer:
public class BoardTimer extends Board{
public function BoardTimer(dimention:uint)
{
boardSide2 = dimention;
super(dimention);
gameTimerBox = new TextField();
myTimer = new Timer(1000,count);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.start();
}
}
And some BoardTimer methods:
function countdown(event:TimerEvent):void
{
gameTimerBox.x = 700;
gameTimerBox.y = 200;
gameTimerBox.textColor = 0xFFFFFF;
gameTimerBox.text = String((count)-myTimer.currentCount);
if (gameTimerBox.text == "0")
{
gameOver();
gameTimerBox.text = String("Game Over");
}
addChild(gameTimerBox);
}
function gameOver()
{
trace(Board(parent).boardSide);
}
In one frame I have this:
dimention=10;
var boardTimer_mc= new BoardTimer(dimention);
boardTimer_mc.x=25;
boardTimer_mc.y=25;
addChild(boardTimer_mc);
and in another I have this:
var dimention:uint=10;
var board_mc: Board = new Board(dimention);
board_mc.x=25;
board_mc.y=25;
addChild(board_mc);
BoardTimer is doing all that Boardis doing but I'm failing to get access to Board methods and variables. I've tried trace(Board(parent).boardSide);, trace(Board(this.parent).boardSide); and trace(Board(this.parent.parent).boardSide); and nothing.
What am I doing wrong?

parent doesn't refer to base class or the parent class you derived from. It refers to the parent in the displaylist on the stage. (read this)
Use super keyword for referring to the base class. Also, when you are inheriting the class, all the protected & public methods & variables would be available as it is in the derived class.

Related

Error #1009: when listening to a button that exists on stage as3

I'm developing a game using as3. It is my first time using flash and as3.
My problem is that I have a button "callBasket" exists on stage, and it's an instance of a class called "CallMethod" my code is as follows:
public class SweetBasket extends Basket{
var basketButtonSweet:BasketButtonSweet = new BasketButtonSweet;
public function SweetBasket() {
}
override protected function clickButton (event:MouseEvent):void{
stage.addChild(basketButtonSweet);
basketButtonSweet.x = 547;
basketButtonSweet.y = 162;
basket = "sweet";
call = stage.getChildByName("callBasket") as CallMethod;
call.addEventListener(MouseEvent.CLICK, onClick);// here is my problem
}
protected function onClick(event:MouseEvent):void{
clicked = true;
trace(clicked);
}
And this is my Basket clas, although I don't think it matters.
public class Basket extends SimpleButton{
var basketButton:BasketButton;
var basket:String;
var call:CallMethod;
public var clicked:Boolean = new Boolean(false);
public function Basket() {
addEventListener(MouseEvent.CLICK, clickButton);
}
protected function clickButton (event:MouseEvent):void{
}
using addEventListener gives me an error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at OOPGame::SweetBasket/clickButton()
Any idea why is this error happening and what have I done wrong?
It pretty much looks like callBasket" does not exist on stage(/is placed somewhere else but not on stage directly). To make sure it really exists, add a trace after "call = stage.getChildByName("callBasket") as CallMethod;" trace("call exists: " + call); what does the trace state?
It looks like element is simply not added to the stage. Check the code fragment where you add element with name "callBasket". Also check that "callBasket" is instance of class CallMethod (or it's inheritor).

AS3 : yet another 1009 error: where's that null object

I've got 1009 error, but I can't find that null object. Can someone point it out to me?
[Fault] exception, information=TypeError: Error #1009: Cannot access a
property or method of a null object reference.
[Fault] exception, information=TypeError: Error #1009: Cannot access a
property or method
of a null object reference. at
Square/draw()[/Users/si/Dropbox/ac3/square/src/Square.as:21] at
Start/drawSquare()[/Users/si/Dropbox/ac3/square/src/Start.as:35] at
starling.events::EventDispatcher/invokeEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/EventDispatcher.as:146]
at
starling.events::EventDispatcher/dispatchEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/EventDispatcher.as:117]
at
starling.display::DisplayObject/dispatchEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObject.as:398]
at
starling.display::DisplayObjectContainer/broadcastEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObjectContainer.as:379]
at
starling.display::DisplayObjectContainer/broadcastEventWith()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObjectContainer.as:389]
at
starling.display::DisplayObjectContainer/addChildAt()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObjectContainer.as:135]
at
starling.core::Starling/initializeRoot()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:439]
at
starling.core::Starling/initialize()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:410]
at
starling.core::Starling/onContextCreated()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:649]
It's starling project it it matters.
Here's the code:
package {
import starling.display.*;
import com.greensock.TweenLite;
import com.greensock.easing.Linear;
public class Square extends Sprite implements ISquare {
public const square:Quad = new Quad(100, 100);
private var direction:Boolean;
private var stopped:Boolean;
private var speed:int;
public function Square() {
}
public function draw():void{
addChild(square);
square.color = 0x4500FF;
direction = new Boolean(true);
stopped = new Boolean(false);
speed = new int(stage.stageHeight);
trace("vars init complete");
down();
}
...
Here's the whole soure on dropbox: https://www.dropbox.com/sh/9x2q93o2ff1fsna/AADVJgt5nipDE1pdkgozkOc1a
Okay, so, let's take a look at the relevant code...
Start class
//stuff omitted like imports
public class Start extends Sprite {
public var viewport:Quad = new Quad(1,1);
private var swipe:SwipeGesture;
private var call:Square = new Square();
public function Start() {
super();
addEventListener(Event.ADDED_TO_STAGE, drawSquare);
}
private function drawSquare(event:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, drawSquare);
viewport.width = stage.stageWidth;
viewport.height = stage.stageHeight;
viewport.color = 0x414141;
addChild(viewport);
swipe = new SwipeGesture(viewport);
swipe.addEventListener(GestureEvent.GESTURE_RECOGNIZED, onSwipe);
trace("gesture listener added");
call.draw();
}
//stuff omitted
}
Square class
//imports omitted
public class Square extends Sprite implements ISquare {
public const square:Quad = new Quad(100, 100);
private var direction:Boolean;
private var stopped:Boolean;
private var speed:int;
public function Square() {
}
public function draw():void{
addChild(square);
square.color = 0x4500FF;
direction = new Boolean(true);
stopped = new Boolean(false);
speed = new int(stage.stageHeight);
trace("vars init complete");
down();
}
//stuff omitted
}
When I manually read your code, I see that this is what happens:
Start.constructor adds eventlistener
eventListener triggers, start.drawSquare
adds viewport, does stuff with swipegesture...
draws square
Square.draw is called
Square adds a quad to itself
sets some colors and variables
direction to true
stopped to false
speed to stage.stageHeight
Wait, stage? stage has not been mentioned around Square yet. I think it's null. And in fact, when you look at the stack trace of the error, you can see this. It says it goes wrong at at Square/draw() in /Users/si/Dropbox/ac3/square/src/Square.as:21. And line 21 of Square.as is speed = new int(stage.stageHeight); This shows that one of the mentioned objects on that line is null or otherwise undefined. Via a process of elimination, we can see that speed has already been declared, and is being assigned to and is thus irrelevant; the int class is defined or the compiling would have gone wrong; and all we are left with is either stage being null or stage.stageHeight being undefined.
The documentation says Stage.stageHeight is an int. It's a property of stage, and since it's a primitive type, it's never null or otherwise undefined (not in actionscript, anyway). So that leaves us with stage: the call instance of Start has never been added to stage, thus stage is null, thus it nulls on
speed = new int(stage.stageHeight)
To fix this, either pass the draw function of Square a reference to stage... or, and this seems to be the better solution, given what you want to do, add call (that's the Square instance) to stage before drawing it.

AS3 - TypeError: Error #1009

I'm trying to create a system that puts each block in a block Array which I can use to easily add blocks to the stage via XML, however I'm getting
[Fault] exception, information=TypeError: Error #1009: Cannot access a property or method of a null object reference.
When it initializes the 'blockStone'.
Here's my main Block class, each block is initialized here.
package com.snakybo.platformengine.block {
import flash.display.MovieClip;
public class Block extends MovieClip {
public static var blockList:Array = [];
public static const blockStone:Block = (new BlockStone(0));
public var blockID:int;
private var mc:MovieClip;
public function Block(blockID:int, mc:MovieClip) {
if (blockList[blockID] != null) {
throw new Error("Slot " + blockID + " is already occupied by " + blockList[blockID] + " when adding " + this);
} else {
blockList[blockID] = this;
this.blockID = blockID;
this.mc = mc;
mc.x = 100;
mc.y = 100;
addChild(mc);
}
}
}
}
Here's the BlockStone class:
package com.snakybo.platformengine.block {
public class BlockStone extends Block {
public function BlockStone(blockID:int) {
super(blockID, new stone());
}
}
}
FlashDevelop refers to this line when it errors:
public class BlockStone extends Block {
Here's the stack trace:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at global$init()[C:\Users\Kevin\Desktop\Extra\Code\Actionscript\PlatformEngine\src\com\snakybo\platformengine\block\BlockStone.as:3]
at com.snakybo.platformengine.block::Block$cinit()
at global$init()[C:\Users\Kevin\Desktop\Extra\Code\Actionscript\PlatformEngine\src\com\snakybo\platformengine\block\Block.as:5]
at com.snakybo.platformengine::Game()[C:\Users\Kevin\Desktop\Extra\Code\Actionscript\PlatformEngine\src\com\snakybo\platformengine\Game.as:13]
at com.snakybo.platformengine::Main/init()[C:\Users\Kevin\Desktop\Extra\Code\Actionscript\PlatformEngine\src\com\snakybo\platformengine\Main.as:20]
at com.snakybo.platformengine::Main()[C:\Users\Kevin\Desktop\Extra\Code\Actionscript\PlatformEngine\src\com\snakybo\platformengine\Main.as:11]
I'm pretty sure it's a problem with AS3, since this method works in Java. I'm open to suggestions on better ways to do this in AS3 using block ID's defined in an XML file.
Can anyone explain why this is happening?
It looks like you're instantiating a new Blockstone before you get through the Block constructor. Try simply declaring the public static const blockStone:Block; without setting a value to it first, and then set it in Block's constructor.

as3 - Creating common objects for all methods

I'm building an application using Flash CS6 and AS3, where there will be loads of texts. So I want to create only one text format object for all of them. I am using this code:
public class MyClass extends MovieClip {
public var formatTitle = new TextFormat();
formatTitle.size = 50; <-- ERROR HERE
public function MyClass(){
buildHome();
}
public function buildHome(){
var title:TextField = new TextField();
title.text = "HOME";
title.defaultTextFormat = formatTitle;
addChild(title);
}
}
But I'm getting the error: Access of undefined property formatTitle where it says formatTitle.size = 50. But it's here above it! What am I missing?
Thanks in advance.
You need to move formatTitle.size = 50; at the beginning of the constructor. You can't have code like this outside of a method.
public function MyClass(){
formatTitle.size = 50;
buildHome();
}

when does the stage become initialised?

I have a singleton class that inherits from sprite so that it can access the stage, like this..
package
{
import flash.display.Sprite;
public class C extends Sprite
{
private var _grid:Array = new Array();
public function get Grid():Array
{
return _grid;
}
private static var _instance:C;
public static function get Instance():C
{
if (_instance == null)
{
_instance = new C();
}
return _instance;
}
function C()
{
this.InitGrid();
}
private function InitGrid():void
{
var gridWidth:Number = stage.width / 10;
}
}
}
This throws the error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at C/InitGrid()
at C()
at C$/get Instance()
at C()
at Main()
If I replace stage.width with an int the code executes OK.
is this because the object has not been added to the displayList of any children of the stage?
Thanks
Yes. The Sprite will only have a stage property once it's a part of the Display list.
To get the stage you will need to either give your singleton a reference to the stage or add it to the Display list. If you choose the latter you can add a listener Event.ADDED_TO_STAGE, and handle that accordingly inside your singleton.