[英]How to create a series of class instances in a for loop, as3
In my library I have a bunch of classes named tip1, tip2, tip3, tip4...and so on. 在我的库中,有一堆名为tip1,tip2,tip3,tip4等的类。 Is it possible to create one instance of each on the stage using a for loop?
是否可以使用for循环在舞台上创建每个实例的一个实例? I tried this but it didn't seem to work.
我试过了,但是似乎没有用。
var tips:int = 12;
for(var i:int = 1; i<=tips; i++){
var tipName:String = "tip"+i
var tip:MovieClip = new tipName();
tip.name = "tip" + i
tip.x = stage.width;
tip.y = 0;
addChild(tip);
}
Any help would be appreciated. 任何帮助,将不胜感激。 Thanks!
谢谢!
You were missing the "getDefinitionByName" part. 您缺少“ getDefinitionByName”部分。
// Up top
import flash.utils.getDefinitionByName;
// Down below
var tips:int = 12;
for (var i:int = 1; i < tips; ++i ) {
var myClass:Class = getDefinitionByName('tip' + i) as Class;
var tip:Object = new myClass();
tip.name = "tip" + i;
....
}
Instead of 代替
var tip:MovieClip = new tipName();
Try (written from memory) 尝试(从内存写入)
var clazz:Class = getDefinitionByName(tipName) as Class;
var tip:MovieClip = new clazz();
Also, you generally want to use stage.stageWidth
instead of stage.width
, since the latter will return the stage bounding box width (which might not be the same as the area the swf file covers). 另外,您通常要使用
stage.stageWidth
而不是stage.width
,因为后者将返回舞台边界框的宽度(可能与swf文件覆盖的区域不同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.