AS3 Removechild Addchild issue/error

846 Views Asked by At

I have been looking for an answer for hours:

My program:

Step I) When I click on a button, it displays a bitmap through addchild; Step II) When I click on another button, it should remove the bitmap through removechild;

Step I) works perfectly but step II) doesn't work.

You'll find below some parts of my code:

First, I declare:

public var ajoutcarte4:MovieClip;

Secondly, In the main function I wrote:

var ajoutcarte4:Bitmap = new Bitmap();

Then, in a sub function triggered by the first button, I add the Bitmap to the stage (fl_bitmap is a function returning a Bitmap item):

ajoutcarte4 = fl_bitmap(couleur4+figure4);
ajoutcarte4.x=445;
ajoutcarte4.y=370;
addChild(ajoutcarte4);

So far so good but when I want to remove the child through another sub function triggered by a second button:

removeChild(ajoutcarte4);

It doesn't work because ajoutecarte4 is apparently null... Error 2007 when i get red of my condition...

2

There are 2 best solutions below

0
On

You've declared a field ajoutcarte4 of type MovieClip, but then in your function, you declare a local variable ajoutcarte4 of type Bitmap, which is then added to the stage.

In the second function, you try to remove the field MovieClip, which has never been instantiated - and thus produces the error.

Change your declaration to this:

public var ajoutcarte4:Bitmap;

and call:

ajoutcarte4 = new Bitmap(); 

(without the var). Then it all should work correctly.

0
On

change this

public var ajoutcarte4:MovieClip;

to

public var ajoutcarte4:Bitmap;


Then take out this line completely

var ajoutcarte4:Bitmap = new Bitmap();


And lastely

// add this like with this code
ajoutcarte4 = new bitMap()
ajoutcarte4 = fl_bitmap(couleur4+figure4);
ajoutcarte4.x=445;
ajoutcarte4.y=370;
addChild(ajoutcarte4);