3

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

如何通过 ".name" 引用影片剪辑?

我试图寻找解决方案,但我找不到任何东西。基本上,我使用循环将一组电影剪辑添加到舞台,所以我发现区分它们的方法是给它们一个“某物”的 .name + 循环的“i”。所以现在它们被命名为“something1”、“something2”、“something3”等。

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

something1.gotoAndStop(2);

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

4

3 回答 3

7

你想使用 getChildByName("name")更多信息

导入 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);
于 2012-07-26T17:07:41.427 回答
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);

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

于 2012-07-26T21:04:09.800 回答
1

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

var something1:MovieClip = stage.getChildByName("something1");
something1.gotoAndStop(2);
于 2012-07-26T17:08:36.510 回答