2012-07-26 88 views
3

Yay,另一個簡單的noobie as3問題。AS3參考movieclip通過.name屬性

如何通過「.name」引用動畫片段?

我試着尋找解決方案,但找不到任何東西。基本上我有一套使用循環添加到舞臺上的影片剪輯,所以我發現區分它們的方式是給它們一個「something」的名字+ Loop的「我」。所以現在他們被命名爲「something1」,「something2」,「something3」等。

現在,我需要發送一些到特定的框架。通常我會這樣做:

something1.gotoAndStop(2); 

但「something1」不是實例名稱,只是「.name」。我找不到引用它的方法。

回答

8

要使用getChildByName( 「名稱」)more info

進口的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); 
+0

每當我使用getChildByName(「something1」);我得到一個「標籤必須是簡單的標識符」錯誤。 – FoxLift 2012-07-26 17:12:17

+0

我會處理一個快速示例,一秒... – Boyd 2012-07-26 17:14:21

+0

好吧我添加了上面的代碼並進行了測試。應該工作得很好。 – Boyd 2012-07-26 17:22:55

1

您可以使用父級按名稱獲取子級。如果父母是舞臺:

var something1:MovieClip = stage.getChildByName("something1"); 
something1.gotoAndStop(2); 
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); 

注意,我也取代許多鬆散的數字與常量和VAR這也將有助於你的編譯器通知錯誤。

+0

感謝您的有益建議! – FoxLift 2012-07-30 17:08:18