spaderdabomb
spaderdabomb

Reputation: 942

Changing text field of button in for loop

I'm making a level select screen and I need the text field to display different level numbers for each level. I don't really see what I'm doing wrong here, but I'll go over what I did and post the relevant code.

I have a button class (linked) and inside the symbol I have a dynamic text field. I have two classes of relevance, LevelSelectScreen and LevelSelectButtons (pretty self-explanatory what they are). I thought it would be really easy to change the text if I did it inside the LevelSelectButtons class, by simply doing levelText.text = "Wanted Text", where levelText is the given instance name for my button (just a text field on top of my graphic for the button). Unfortunately, this gives the oh so common and annoying error: TypeError: Error #1009: Cannot access a property or method of a null object reference.

I tried doing virtually the same thing in my LevelSelectScreen class during my loop, but I got the same error. Help on how to get this levelText to work is greatly appreciated! Here is the relevant code.

LevelSelectScreen

    public class LevelSelectButtons extends SimpleButton {

        public var levelNumber:int;
        public var levelSelectScreen:LevelSelectScreen;

        public function LevelSelectButtons(i) {

            x = 200;
            y = 100 + 50*i;
            addEventListener(MouseEvent.CLICK,LevelSelectClicked,false,0,true)
            levelNumber = i;
            levelText.text = "Level" + i;
        }

    }

LevelSelectScreen

public class LevelSelectScreen extends MovieClip {

    public var levelSelectButtons:LevelSelectButtons;
    public var mainMenuButton:MainMenuButton;

    public function LevelSelectScreen() {

            for (var i:int = 1; i<=2; i++) 
            {
                levelSelectButtons = new LevelSelectButtons(i);
                addChild(levelSelectButtons);
            }
    }

}

Upvotes: 0

Views: 93

Answers (2)

Cadin
Cadin

Reputation: 4649

You can't have a dynamic text field in a SimpleButton.
Annoying, I know.

Simple fix would be to have LevelSelectButton wrap a SimpleButton instead of extend it. Then your text field would be inside LevelSelectButton on top of a text-less SimpleButton. (Be sure to set mouseEnabled to false on the text field so it doesn't interfere with mouse events on the SimpleButton.

A more complex option would be to write your own custom button class.
It's not actually that difficult, but might be overkill for what you're trying to do here.

Upvotes: 2

ToniK
ToniK

Reputation: 64

its because you haven't declared levelText variable and you are trying to access it, therefor Cannot access a property or method of a null object reference.

Upvotes: -1

Related Questions