Search code examples
actionscript-3airflash-cc

EventListener and Dynamically added MovieClips. (AS3)


I'm trying to create a small game (it's more about learning how to than making a compelling game). It can be resumed like this: User choose a building in a menu and place it on the stage. When clicking on the newly created building, s/he can choose to upgrade it. (For those that play games like Clash of Clans, it's what i'm trying to do). I have my menu, and can place buildings without problem, but I can't click on them. Here is the beginning of my code:

var build:int=0; //variable that defines which building to place on stage

menuBuilding.house.addEventListener(MouseEvent.CLICK, fnChooseHouse); //when click on House in Building Menu
function fnChooseHouse (e:Event):void{
    build = 1; //building to place is a House.
}

city.addEventListener(MouseEvent.CLICK, mouseClickEvent);

function mouseClickEvent(e: MouseEvent): void {
    if (build == 0) { //if building not chosen, do nothing
        return
    } else if (build == 1) { // if building is a house
        var house1: house = new house();
        addChild(house1); //add instance of the house
        house1.x = stage.mouseX;
        house1.y = stage.mouseY; // place the house where I clicked
        build = 0; //reset the variable.
        house1.mouseChildren=true; //allow instance of house to be clicked.
    }
};

My problem is that there is gonna be a lot of houses (and other buildings). I've tried to name them and push them in an array (so I can access them with a for each...in loop), but it doesn't work.

Someone has an idea? (Btw, I'm still learning AS3 as I go, so I'm not using external .as file yet, still in timeline). Thanks in advance :)


Solution

  • Your new instance of a house has no click event listener on it, which would be why you "can't" click on it. By setting "mouseChildren" to true might not do anything as this variable might already be true by default.

    In the future, how many houses/buildings will you have? If it is many, I'm not sure this path may be the most efficient down the road.