This looks long but it’s a really simple question. With the following code:
public class Map extends MovieClip
{
var dragdrops:Array;
var numOfMatches:uint = 0;
var speed:Number = 25;
public function Map()
{
// constructor code
var dragdrops = [one_mc,two_mc,three_mc,four_mc,five_mc,six_mc];
var currentObject:DragDrop;
for (var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
currentObject.target = getChildByName(currentObject.name + "_target");
}
}
public function match():void
{
numOfMatches++;
if(numOfMatches == dragdrops.length)
{
win.addEventListener(Event.ENTER_FRAME, winGame);
}
}
I get this error
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at Map/match()[G:_flash\edu\drag_drop\Map.as:34]
at DragDrop/drop()[G:_flash\edu\drag_drop\DragDrop.as:41]
I assume it’s because i’m referencing the global array “dragdrops” which currently is a null value.
However the code below works perfectly, by passing the dragdrops.length value to another global variable.
public class Map extends MovieClip
{
var dragdrops:Array;
var dragdropslength:Number = 0;
var numOfMatches:uint = 0;
var speed:Number = 25;
public function Map()
{
// constructor code
var dragdrops = [one_mc,two_mc,three_mc,four_mc,five_mc,six_mc];
var currentObject:DragDrop;
for (var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
currentObject.target = getChildByName(currentObject.name + "_target");
}
dragdropslength = dragdrops.length
}
public function match():void
{
numOfMatches++;
if(numOfMatches == dragdropslength)
{
win.addEventListener(Event.ENTER_FRAME, winGame);
}
}
While this works fine I was wondering if there was a more elegant solution to be able to reference the dragdrops value from within the Map() constructor without the extra variable.
You can assign to “dragdrops” directly in the constructor, thereby initializing the instance variable. Just remove the preceding “var” in the first line of the Map constructor.