2017-01-01 90 views
2

我有一個場景,包括所有使用addChild(...)將它們中的一些帶到舞臺上的動畫片段,精靈,圖形。如何從AS3中的場景中刪除所有影片剪輯,精靈和圖形?

我想刪除所有這些,因爲在我去其他場景時我仍然可以看到它們。

我用下面的代碼,但它顯示我以下提到的錯誤:

btn.addEventListener(MouseEvent.CLICK,removing); 

function removing(e:MouseEvent):void 
{ 
    while (stage.numChildren > 0) 
    { 
    stage.removeChildAt(0); 
    } 

} 

錯誤:

類型錯誤:錯誤#1009:無法訪問空對象引用的屬性或方法。 at Show_fla :: MainTimeline/removal()

在此先感謝您的時間和幫助!

回答

2

,因爲它表明,它不與while循環工作,它正在與for循環|:

btn.addEventListener(MouseEvent.CLICK,removing); 

function removing(e:MouseEvent):void 
{ 
var i:int = 0; 
for (i=stage.numChildren-1; i>=0; i--) 
{ 
    stage.removeChildAt(i); 
} 
} 
1

酒店DiaplayObject.stage定義僅在給定的DisplayObject實際上是附着階段。只要刪除包含刪除代碼的Sprite/MovieClip,它的.stage更改爲null,下一個條件檢查stage.numChildren自然會失敗。你應該保留一個局部變量的階段引用。

btn.addEventListener(MouseEvent.CLICK,removing); 

function removing(e:MouseEvent):void 
{ 
    var aStage:Stage = stage; 

    while (aStage.numChildren > 0) 
    { 
    aStage.removeChildAt(0); 
    } 
} 
+0

這避免了錯誤,但刪除[對象MainTimeline]太。 因此,第一次循環後沒有更多的孩子。 @Organis – tatactic

1

如果添加了要刪除的對象的痕跡,你會看到你刪除[對象MainTimeline],所以你甚至不需要一個循環。

在您的代碼中刪除[對象MainTimeline]並刪除所有剪輯。 在while循環中,它不會在for循環中引發錯誤。

function removing(e:MouseEvent):void { 
    var i:int = 0; 
    for (i=stage.numChildren-1; i>=0; i--) 
    { 
     trace("removing : " + (stage.getChildAt(i))); 
     stage.removeChildAt(i); 
    } 
} 

輸出:

removing : [object MainTimeline] 

使您免除對象[對象MainTimeline],沒有更多的孩子來去除。

function removing(e:MouseEvent):void { 
    trace("removing : " + (stage.getChildAt(0))); 
    stage.removeChildAt(0); 
} 

可能會給你同樣的輸出:

removing : [object MainTimeline] 

所以你不要就算[對象MainTimeline]被刪除需要一個循環。

我沒有在相同的條件下測試它,所以請告訴我們,如果你有相同的輸出。

我建議你檢查從@LukeVanIn,解釋了difference between stage, root and main timeline

[編輯]

function removingWhile(e:MouseEvent):void { 
    while (stage.numChildren > 0){ 
    count++; 
    trace("removing : " + (stage.getChildAt(0))); 
    trace ("number of iterations = " + (count++).toString()) 
    stage.removeChildAt(0); 
    } 
} 

將輸出的答案:

刪除:對象MainTimeline] 迭代次數= 1

TypeError:Error#1009 ... 在Untitled_fla :: MainTimeline/removingWhile()

[/編輯]

+0

@Maziar我真的很想知道輸出面板在你的情況下會輸出什麼。 我可能是錯的,但這總是很好用一些trace()函數或try ... catch塊來測試代碼。 – tatactic