I am a newbie, and I have seached and tried for weeks on this, and I cannot get the grip on this. The simple code below gives the "The supplied DisplayObject must be a child of the caller" error.
var square = new squareObj;
addChild(square);
addEventListener(Event.ENTER_FRAME, removeSquare);
function removeSquare(evt:Event):void {
removeChild(square)
}
squareObj is a movieclip in the library which is exported for AS. How can this code be altered to make it work correctly? I guess it's my knowledge on proper oop I'm in lack of, so any links to good tutorials on the matter is appreciated.
Regards H
The problem is that the enter frame listener will be called over and over again. The first time it is called the DisplayObject will indeed be a child of the caller, but after that it will not (since it has already been removed).
So I suggest you do:
var square = new squareObj;
addChild(square);
addEventListener(Event.ENTER_FRAME, removeSquare);
function removeSquare(evt:Event):void {
if (contains(square)) {
removeChild(square)
}
}
either check if the square is indeed a child of this
var square = new squareObj;
addChild(square);
addEventListener(Event.ENTER_FRAME, removeSquare);
function removeSquare(evt:Event):void {
removeEventListener(Event.ENTER_FRAME, removeSquare)
removeChild(square)
}
or remove the event listener, depending on whether or not you need the event for something else than removing the square. Also you should note that you probably won't see the square at all, since it will be removed pretty quickly after it has been added.