【问题标题】:adding items from an array multiple times to the stage将数组中的项目多次添加到舞台
【发布时间】:2011-02-16 09:19:40
【问题描述】:

我有一个通过 11 次的 for 循环:

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 个跟踪“空”。我的问题是,如何在不丢失其属性等的情况下多次添加数组中的项目?

【问题讨论】:

  • 我对你的代码没有问题:public function Test3() { var arr : Array = new Array( new Sprite, new Sprite, new Sprite, new Sprite, new Sprite, new Sprite ); for(var i:uint = 0;i&lt;10;i++){ addChild(arr[currentItem]); trace(arr[currentItem]); currentItem++; if(currentItem == arr.length){ currentItem = 0; } } } private var currentItem:uint;你的问题可能来自你没有初始化 currentItem,所以你的代码只在第一次调用时工作

标签: actionscript-3


【解决方案1】:

您的循环本身没有任何问题。但是,一个 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]);
}

【讨论】:

  • 它不应该是同一个孩子,我只想从那个孩子创建新实例,所以每个实例都不同但具有相同的属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
  • 2013-03-10
  • 2014-08-29
  • 1970-01-01
相关资源
最近更新 更多