所以,我正在以编程方式将movieclip对象添加到主时间轴上。 在那些影片剪辑中使用计时器事件,这样他们就会在添加到舞台后移动。
所以当我的游戏结束时,我想从舞台上删除movieclip对象,我可以这样做,但是它会导致错误,因为对象的监听器仍然存在。
我无法从主时间轴访问movieclip对象时间轴中的代码以删除侦听器,并且我不知道如何在删除它们时从动画片段时间轴中删除侦听器!
我希望这是有道理的!
帮助!
答案 0 :(得分:1)
您的MovieClip可以侦听Event.REMOVED_FROM_STAGE,以编程方式删除您之前添加的所有事件侦听器。以下是一些示例代码,用于说明如何完成。
// add this code to an ActionScript class that extends Sprite
// call initClips() in the constructor
private var _clipA:MovieClip;
private var _clipB:MovieClip;
private var _clipACount:int;
private var _clipBCount:int;
private function initClips():void
{
// create 2 movieclips and add some common event listeners
_clipA = new MovieClip();
_clipA.addEventListener(Event.ADDED_TO_STAGE, onClipAddedToStage);
_clipA.addEventListener(Event.REMOVED_FROM_STAGE, onClipRemovedFromStage);
_clipA.addEventListener(Event.ENTER_FRAME, onEnterFrameClipA);
_clipB = new MovieClip();
_clipB.addEventListener(Event.ADDED_TO_STAGE, onClipAddedToStage);
_clipB.addEventListener(Event.REMOVED_FROM_STAGE, onClipRemovedFromStage);
_clipB.addEventListener(Event.ENTER_FRAME, onEnterFrameClipB);
_clipACount = 0;
_clipBCount = 0;
addChild(_clipA);
addChild(_clipB);
}
private function onClipAddedToStage(event:Event):void
{
var clip:MovieClip = event.currentTarget as MovieClip;
if(clip == _clipA)
{
// position movieclip to dummy values
clip.x = 40;
clip.y = 40;
}
else if(clip == _clipB)
{
clip.x = 200;
clip.y = 100;
}
}
private function onClipRemovedFromStage(event:Event):void
{
var clip:MovieClip = event.currentTarget as MovieClip;
// good habit to null check in case "as" casting fails
if(clip != null)
{
// remove event listeners for this movieclip instance
clip.removeEventListener(Event.ADDED_TO_STAGE, onClipAddedToStage);
clip.removeEventListener(Event.REMOVED_FROM_STAGE, onClipRemovedFromStage);
// there is no penalty for trying to remove event listeners that were not added to this object instance
clip.removeEventListener(Event.ENTER_FRAME, onEnterFrameClipA);
clip.removeEventListener(Event.ENTER_FRAME, onEnterFrameClipB);
}
}
private function onEnterFrameClipA(event:Event):void
{
_clipACount++;
trace("onEnterFrame for clipA " + _clipACount);
if(_clipACount > 10)
{
// for demonstration purposes
// remove self after a few frames pass
removeChild(_clipA);
}
}
private function onEnterFrameClipB(event:Event):void
{
_clipBCount++;
trace("onEnterFrame for clipB " + _clipBCount);
if(_clipBCount > 20)
{
removeChild(_clipB);
}
}
答案 1 :(得分:0)
当从舞台中删除DisplayObject时,有一些事件要接收通知。只需为Event.ADDED,Event.ADDED_TO_STAGE,Event.REMOVED和Event.REMOVE_FROM_STAGE设置监听器即可实现MovieClip的实时循环。添加MovieClip时启动内容。删除MovieClip时删除侦听器,停止计时器等。