2011-02-16 54 views
1

我有一个for循环至极经过11次:从阵列多次ading项阶段

private var currentItem:uint; 
for(var i:uint = 0;i<10;i+){ 
    addChild(arr[currentItem]); 
    currentItem++; 
    if(currentItem == arr.length){ 
    currentItem = 0; 
    } 
} 

所以问题是,该阵列只包含6个项目。因此,当涉及第6项时,currentItem将重置,并且接下来的4项要添加的项再次是阵列中的第4项。现在,当我追踪这些项目时,最后4条曲线为“null”。我的问题是,我怎么可以从数组中添加项目多次,而不会失去它的属性等?

+0

我有你的代码没有问题:'公共功能Test3的() \t \t { \t \t \t VAR ARR:阵列=新的Array( \t \t \t \t新雪碧, \t \t \t \t新的雪碧, \t \t \t \t新的雪碧, \t \t \t \t新的Sprite, \t \t \t \t新的Sprite, \t \t \t \t新的Sprite \t \t \t); \t \t \t为(VAR I:UINT = 0; I <10; i ++在){ \t \t \t \t的addChild(ARR [CURRENTITEM]); \t \t \t \t trace(arr [currentItem]); \t \t \t \t currentItem ++; \t \t \t \t如果(CURRENTITEM == arr.length){ \t \t \t \t \t CURRENTITEM = 0; \t \t \t \t} \t \t \t} \t \t} \t \t \t \t私人VAR CURRENTITEM:单元;` 您的问题,从你不initialyze CURRENTITEM事实也许来,所以你的代码的工作只为首先调用 – 2011-02-16 09:42:19

回答

2

你的循环没有任何内在的错误。但是,DisplayObject只能在显示列表中显示一次。它不能有多个父母或多次成为同一父母的孩子。这就是为什么你的代码不工作。

更新:

如果你想从类,你可以做到这一点的名单,但你目前的做法不会工作,创建新实例。这就是你需要做什么:

// the square bracket notation is shorthand for creating an array. 
// fill the array with references to *classes* not instances 
var classes:Array = [ MyClassOne, MyClassTwo, MyClassThree ]; 

// we run the loop much as you did, but we can make it much more compact 
// by using the modulus operator 
// since the array is full of classes, we can use the new operator to 
// create new instances of those classes and add them to the display-list 
for(var i:uint = 0; i < 10; i++){ 
    addChild(new classes[i % classes.length]); 
} 
+0

它不应该是同一个孩子,但我只是想从该孩子创建新的实例,所以每个实例是不同的,但具有相同的属性。 – vincent 2011-02-16 10:18:04