I'm having problems with addChild() from a class.
I have a Ball class:
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);
}
}
}
Where BallImage is a movieClip in the library exported for ActionScript.
I add it to the main like this:
import Ball;
var littleBall:Ball = new Ball();
addChild(littleBall);
littleBall.x=100;
littleBall.y=100;
The image loads just fine, and I can see it on screen. But I get a stack Overflow error. Everything seems to work just fine... So I can't figure out what the problem is.
Edit: If I move the addChild() to the constructor of Ball, the error goes away. Still don't know what that means. Why can't I add it just when it loads?
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.