Mykybo
Mykybo

Reputation: 1499

Flash access of undefined property

So I am making my first game in flash (more like converting to flash, already have it in JS). I am getting this error:

"access of undefined property item"

and I have no idea why.

addEventListener(Event.ENTER_FRAME, onEnterFrame);

var Entities:Array = new Array();

//Create player
var Player = new Character();
Player.x = stage.stageWidth / 2 - Player.radius;
Player.y = stage.stageHeight / 2 - Player.radius;

Entities.push(Player);
stage.addChild(Player);

function onEnterFrame(event:Event):void
{   
    for each (item in Entities)
    {
        item.update();
    }
}

I will be adding many Monsters into entities as well, that's why it's an array.

Upvotes: 1

Views: 248

Answers (1)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

The error is because you are referencing a variable called item but you haven't defined it to the compiler.

for each (item in Entities)

Define (var) the item and you will no longer receive the error:

for each (var item:Character in Entities)

I would recommend using a Vector instead of an Array (They are basically the same except in a Vector every object has to be of the defined type. Then you don't have to cast for the compiler to know what kind of object is in your array.

var Entities:Vector.<Character> = new Vector.<Character>();

If you do continue to use Array - you'll need to cast your items in order to access their properties/methods without a compiler error.

Character(item).update(); //since items in arrays are just stored as objects, you need to tell AS3 that this item is a Player class

Upvotes: 1

Related Questions