|
-
Senior Member
Multiple Variables in a for statement
Hello,
I'm trying to declare a few variables in a for statement using the variable in the for statement. In older flash versions I would use something like this.
Code:
for(a=0;a<10;a++) {
_root["variable"+a] = "Some text "+a;
}
But now I can't get it to work in AS3. I've tried doing different variations of...
Code:
for(var a:int=0;a<10;a++) {
var ["variable"+a]:String = "Some text "+a;
}
But no luck.
If anyone knows an alternate way to declare variables and use a different variable to help name it, please help me!
Thanks in advance!
~Bill
So many Ideas
So little Time
-
Two part answer. First part: You don't really want to do this. Instead, you probably want to use an Array or Vector.
Code:
var texts:Array = [];
for (var a:int = 0; a < 10; a++){
texts.push("Some text "+a);
}
trace(texts[2]); //Some text 2
Vector:
Code:
var texts:Vector.<String> = new Vector.<String>();
for (var a:int = 0; a < 10; a++){
texts.push("Some text "+a);
}
trace(texts[2]); //Some text 2
Second part: If you really want to declare properties on the root at runtime, you can do so if the root is a MovieClip or other Dynamic class. These are properties, not variables, and must always be accessed relative to the root rather than with just the name.
Code:
var rootmc:MovieClip = MovieClip(root);
for(var a:int=0;a<10;a++) {
rootmc['variable'+a] = "Some text "+a;
}
trace(rootmc['variable2']); //Some text 2
Seriously, don't do that.
-
Senior Member
Thanks!
That help a bit, but I have another question for you.
I shouldve been a little more descriptive as to what I was going to get at.
Is there an easier way to create consecutive numbered TextFields without doing in that method?
I did change some other variables to arrays instead of the other way, but not sure if I'd be able to do the same thing with text fields.
Thanks again!
~Bill
So many Ideas
So little Time
-
You can do the same Array thing with TextFields. In fact, you can do the root[name] thing with them too. They're not special.
Code:
var texts:Array = [];
for (var a:int = 0; a < 10; a++){
var atext:TextField = new TextField();
aText.text = "Some text "+a;
aText.y = a*10; //just so they're not in the same place on stage.
addChild(aText);
texts.push(aText);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|