开发者

adding items from an array multiple times to the stage

开发者 https://www.devze.com 2023-02-11 13:36 出处:网络
I have a for loop which passes 11 times: private var currentItem:uint; for(var i:uint = 0;i<10;i+){ addChild(arr[currentIt开发者_JAVA百科em]);

I have a for loop which passes 11 times:

private var currentItem:uint;
for(var i:uint = 0;i<10;i+){
    addChild(arr[currentIt开发者_JAVA百科em]);
    currentItem++;
    if(currentItem == arr.length){
    currentItem = 0;
    }
}

So the problem is that the array only contains 6 items. So when it comes to the 6th item the currentItem resets and the next 4 items that are getting added are the 4 first from the array again. Now when I trace the items, the last 4 trace "null". My question is, how can I add items from the array multiple times without losing its properties etc?


There's nothing inherently wrong with your loop. However, a DisplayObject can only be on the display list once. It can't have multiple parents or be a child of the same parent many times. That's why your code isn't working.

Update:

If you want to create new instances from a list of Classes you can do that, but your current approach wont work. This is what you need to do:

// 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号