views:

1507

answers:

3

Hello!

I'm trying to create dynamic balls by using for loop. For some reason I get two objects (trace show 2 balls and their DIFFERENT properties), but on the stage I can see just a last one created.

This is my code:

var randomBall_mc:ball=new ball(); for (i=1; i<3; i++) { addChild(randomBall_mc); randomBall_mc.name="randomBall"+i; randomBall_mc.x=150*i; randomBall_mc.y=175; randomBall_mc.height=20*i; randomBall_mc.width=20*i; trace("randomBall"+i); trace(randomBall_mc.x); trace(randomBall_mc.height); }

Does some one know what is wrong in my code? Thanks

+1  A: 

It seems like you're instantiating the ball only once before the loop instead of doing it for each iteration.

Theo.T
+1  A: 

var randomBall_mc:ball=new ball(); should be inside the for loop in order to create more than ONE "ball"

for (i=1; i<3; i++) { var randomBall_mc:ball=new ball(); addChild(randomBall_mc); randomBall_mc.name="randomBall"+i; randomBall_mc.x=150*i; randomBall_mc.y=175; randomBall_mc.height=20*i; randomBall_mc.width=20*i; trace("randomBall"+i); trace(randomBall_mc.x); trace(randomBall_mc.height);}

OXMO456
A: 

The answer is spot on, but polishing the code up a little:

var ball:Ball;                  // Observe convention: capitalise class names
var i:int = 0;                  // Make sure to type your variables
for (; i < 3; i++) {
    ball = new Ball();
    ball.name = "randomBall"+i;
    ball.x = 150 * i;
    ball.y = 175;
    ball.height = 20 * i;
    ball.width = 20 * i;

    addChild(ball);             // Configure your instance first;
                                // then add it to the display list

    trace("ball:", i, ball.x, ball.height); 
}

Coded Signal