AS3引用.name属性的movieclip

时间:2012-07-26 16:53:17

标签: actionscript-3 flash movieclip

是的,另一个简单的noobie as3问题。

如何通过“.name”引用动画片段?

我尝试寻找解决方案,但我找不到任何东西。基本上我有一组使用循环添加到舞台上的动画片段,所以我发现它们区分它们的方式是给它们一个.name“of something”+ Loop的“i”。所以现在它们被命名为“something1”,“something2”,“something3”等等。

现在,我需要将一些内容发送到特定的框架。通常我会做类似的事情:

something1.gotoAndStop(2);

但“something1”不是实例名称,只是“.name”。我找不到引用它的方法。

3 个答案:

答案 0 :(得分:7)

您想使用getChildByName(“name”)more info

import flash.display.MovieClip;

// create boxes
for(var i:int = 0 ; i < 4; i++){

    var box:MovieClip = new myBox(); // myBox is a symbol in the library (export for actionscript is checked and class name is myBox

    box.name = "box_" + i;
    box.x = i * 100;
    this.addChild(box);

}

// call one of the boxes

var targetBox:MovieClip = this.getChildByName("box_2") as MovieClip;
targetBox.gotoAndStop(2);

答案 1 :(得分:2)

按名称访问内容很容易出错。如果你是新手,这不是一个好习惯。我认为更安全的方法是在循环中存储对您正在创建的内容的引用,例如在数组中,并通过索引引用它们。

示例:

var boxes:Array = [];
const NUM_BOXES:int = 4;
const SPACING:int = 100;

// create boxes
for(var i:int = 0 ; i < NUM_BOXES:; i++){

    var box:MovieClip = new MovieClip(); 

    // You can still do this, but only as a label, don't rely on it for finding the box later!
    box.name = "box_" + i; 
    box.x = i * SPACING;
    addChild(box);

    // store the box for lookup later.
    boxes.push(box); // or boxes[i] = box;
}

// talk to the third box
const RESET_FRAME:int = 2;
var targetBox:MovieClip = boxes[2] as MovieClip;
targetBox.gotoAndStop(RESET_FRAME);

注意,我还用常量和变量替换了许多松散的数字,这也有助于编译器发现错误。

答案 2 :(得分:1)

您可以使用父级来按名称获取子级。如果父母是舞台:

var something1:MovieClip = stage.getChildByName("something1");
something1.gotoAndStop(2);
相关问题