Judging by the amount of keywords my other AS3 post picked up like “Creating a new text loop in AS3”, I was obliged to answer.
Well, creating textfields in a loop is quite simple. Lets define a bare-minimum TextFormat outside of our loop (unless it needs to change per iteration).
var textFormat:TextFormat = new TextFormat("verdana", 11)
By the way, lets use our little trick we learned about assigning dynamic variable names to movieclips here because the same issue applies: we want access to our textfields in case we want to modify them later. The problem is that after this loop, we have no way of accessing them!
Let’s create an array to store our textfield and create a loop to generate our text fields.
var textFormat:TextFormat = new TextFormat("verdana", 11)
// lets create an array to store all of our textfield references.
var textArray:Array = new Arrray()
// and now the loop
for (var i:int; i < 3; i++) {
var textField:TextField = new TextField()
textField.defaultTextFormat = textFormat
textField.text = 'This is my TextField' + i
textField.x = 50*i
addChild(textField)
textArray.push(textField)
}
This would create 3 textFields with text: “This is my TextField0”, 1, 2.
We can now access those textfields (say the x position was too arbitrary) with our textArray.
textArray[0] = our first textField, textArray[1] = our second one, etc. textArray[0].x = 500 // to access each object
Here’s a tip for having more useable text in the textFields. After all, the same thing plus a number is quite boring.
We can make another Array that holds the text each textField is supposed to have.
How about:
var text:Array = new Array('First TextField','TextField Two', 'Anything, really')
Now we can run through our loop again according to how many things are defined in our Array called text.
for (var i:int; i < text.length; i++) {
var textField:TextField = new TextField()
textField.defaultTextFormat = textFormat
textField.text = text[i]
textField.x = 50*i
addChild(textField)
textArray.push(textField)
}
This time, our loop will conveniently create as many textFields as you put in the “text” array. In retrospect, naming the textfield reference array textArray was a bad idea, as it forced me to use an uninformative name for the second array. It probably should have been something like: tfReferenceArray, and tfTextArray.
Hope something was useful. There are endless applications for this stuff.