0

我在课堂上遇到了 addChild() 的问题。

我有一个球类

package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.*;
import Achievement;
public class Ball extends Sprite {
    //the image I want to add
    var mc:MovieClip;

    public function Ball() {
        addEventListener(Event.ADDED, beginClass);
    }

    private function beginClass(event:Event):void {
        mc = new BallImage();
        addChild(mc);
    }

}
}

其中BallImage是为 ActionScript 导出的库中的影片剪辑。

我像这样将它添加到 main 中:

import Ball;
var littleBall:Ball = new Ball();
addChild(littleBall);
littleBall.x=100;
littleBall.y=100;

图像加载得很好,我可以在屏幕上看到它。但我得到一个堆栈溢出错误。一切似乎都很好......所以我无法弄清楚问题是什么。

编辑:如果我将 addChild() 移动到Ball的构造函数,错误就会消失。还是不知道是什么意思。为什么我不能在加载时添加它?

4

2 回答 2

3

Event.ADDED will fire any time the object or any of its children are added to the display list. So it fires once when you add Ball, and then fires recursively every time you add a new BallImage to Ball.

To fix:
Either remove the event listener at the beginning of the beginClass function, or use Event.ADDED_TO_STAGE instead (which you should also probably remove the listener for after it fires).

If you don't specifically need to listen for those events, you could also just call beginClass directly from the constructor and bypass the events altogether.

于 2012-01-10T17:09:41.120 回答
1

The problem is that you never clean up your event listener.

private function beginClass(event:Event):void {
    removeEventListener(Event.ADDED, beginClass);  // add this line
    mc = new BallImage();
    addChild(mc);
}

When you add the BallImage, it triggers the Event.ADDED event again, so you need to remove the listener before you add anything else.

于 2012-01-10T17:11:53.520 回答