0

I have a dynamic textfield with an instance name of hiscoreFirstPlayer. My goal is be able to access all my instances through array. So therefore, I decided to create an array and try to accessing it:

package {
    import flash.display.*;
    import flash.events.*;
    import flash.ui.*;

    private var hiscore:Array = [hiscoreFirstPlayer];

    class Game extends MovieClip {
        //Return null
        trace(hiscore[0]);

        //TypeError: Error #1009: Cannot access a property or method of a null object reference.
        hiscore[0].text = "1000";

        //Return 0
        trace(hiscoreFirstPlayer);

        //Return 1000
        hiscoreFirstPlayer.text = "1000";
        trace(hiscoreFirstPlayer);
    }
}

So what is the proper way to access my instances via array, without returning a null value. It seems that when I put inside the array, is like I am creating a new object and assigning to the variable, thus resulting a null object.

T. Wolf
  • 83
  • 1
  • 9

2 Answers2

1

Looks like variable declaration placement issue.
Declare the varible inside a class.

package {
    import flash.display.*;
    import flash.events.*;
    import flash.ui.*;

    //private var hiscore:Array = [hiscoreFirstPlayer];

    class Game extends MovieClip {

        private var hiscore:Array = [hiscoreFirstPlayer];

        trace(hiscore[0]);

        hiscore[0].text = "1000";
    }
}

I think, basically almost code should be described inside a class except the import statements, the include statements, the use directive and the metadata.

Yasuyuki Uno
  • 2,417
  • 3
  • 18
  • 22
0

First, I would instantiate the Array class like this (personal preference and I know it works):

private var hisscoreFirstPlayer:Array = new Array();

To add elements to an array, use the push method. Something like this:

var p1score: uint;
p1score = 1000; 
// push adds to the top of the stack
hiscoreFirstPlayer.push(p1score); 

Further your understanding of working with arrays. Look into push, pop, shift, and unshift, and splice just for a good start (look here). As you can see, this will only be an array of player 1 scores. Then player 1 can be accessed by calling

hiscoreFirstPlayer[0];

But I would change the array name to allHiScores. Then you could add all player high scores to one array, and potentially call Player n's high score like this:

allHiScores[n-1];
Community
  • 1
  • 1
Neal Davis
  • 2,010
  • 2
  • 12
  • 25