Skip to main content
Known Participant
March 17, 2010
Answered

Can you create multiple variables with a function or a loop?

  • March 17, 2010
  • 1 reply
  • 585 views

I want to dynamically create variables that will create and place instances of a movie clip on the stage at runtime. Is this possible? Here's what I've come up with, I know it's super wrong. Any help is much appreciated:

var counter:Number = 3;

for (var i:int = 0; i<counter; i++)

{

     var a:Number = i

     var a:pill1_mc = new pill1_mc();

     i.x = 600;

     i.y = 55;

     if (i != 0)

     {

          i.y = (i-1).y +36;

     }

}

This topic has been closed for replies.
Correct answer Andrei1-bKoviI

Actually no, it creates a new instance on each iteration. Try it for yourself and see - just addChild(a) on each iteration. Another question, perhaps, is if you want to retain the reference to each instance and somehow address to it in the future. In this case, one of the ways is to store instances in an array and then refer to them as needed - you are on the right track:

var counter:int = 3;
var a:pill1_mc;
var nextY:Number = 0;
var movies:Array = [];
for (var i:int = 0; i < counter; i++)
{
     a = new pill1_mc();
     movies.push(a);
     a.x = 600;
     a.y = nextY;
     addChild(a);
     nextY += 36;
}

1 reply

Inspiring
March 17, 2010

I guess what you mean is this:

var counter:int = 3;
var a:pill1_mc;
var nextY:Number = 0;
for (var i:int = 0; i < counter; i++)
{
     a = new pill1_mc();
     a.x = 600;
     a.y = nextY;
     nextY += 36;
}

Known Participant
March 17, 2010

Andrei, Thanks for correcting my awful structure. This is pretty much what I am trying to do. The only thing is that on each iteration of the for loop it just changes the properties of "a" each time. What I'm trying to figure out is if it is possible to create a new instance of the movieclip on each iteration of the loop. Leaving me with three instances of the movie clip, each with a unique instance name (to possibly be stored in an array)...

Andrei1-bKoviICorrect answer
Inspiring
March 17, 2010

Actually no, it creates a new instance on each iteration. Try it for yourself and see - just addChild(a) on each iteration. Another question, perhaps, is if you want to retain the reference to each instance and somehow address to it in the future. In this case, one of the ways is to store instances in an array and then refer to them as needed - you are on the right track:

var counter:int = 3;
var a:pill1_mc;
var nextY:Number = 0;
var movies:Array = [];
for (var i:int = 0; i < counter; i++)
{
     a = new pill1_mc();
     movies.push(a);
     a.x = 600;
     a.y = nextY;
     addChild(a);
     nextY += 36;
}