Taylor Swift
Taylor Swift

Reputation: 242

Why doesn't my For loop create more than one object on the screen?

Having a bit of a problem. I'm trying to add 10 items to the stage but it is only adding 1. Any insight on what I'm doing wrong?

        public var numCells:Array = [];
        public function addCell():void
        {
            var cell:Cell = new Cell();
            var i:int = 0;
            cell.x = Math.floor(Math.random() * 1366);
            cell.y = Math.floor(Math.random() * 768);
            for(var i:int = 0; i < 10; i++)
            {
                numCells.push(cell);
                addChild(cell);
            }
            return;
        }

Upvotes: 0

Views: 56

Answers (1)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

You are only ever instantiating one cell. calling addChild a second time with the same object passed in doesn't make a copy of that object, it just moves it to the top most 'layer'.

You need to instantiate a new cell inside the for loop. Something like this:

     private function addCells():void {
         for(var i:int = 0; i < 10; i++){
             var cell:Cell = new Cell();
             cell.x = Math.floor(Math.random() * 1366);
             cell.y = Math.floor(Math.random() * 768);

             numCells.push(cell);
             addChild(cell);
         }
    }

Upvotes: 2

Related Questions