Copy link to clipboard
Copied
i've been trying to do something in which when i clicked on a button, it removes one of the child i randomly added. The addChild works fine but not the removeChild. Here's me script :
function randRange(startNum, endNum) {
return Math.floor(startNum +(Math.random()
* (endNum - startNum)));
}
var myBeetle = new beetleBug();
btnADDbeetle.addEventListener(MouseEvent.CLICK,doADDbeetle);
function doADDbeetle(e){
var myBeetle = new beetleBug();
myBeetle.x = randRange(0, 800);
myBeetle.y = randRange(0, 800);
addChild(myBeetle);
}
btnMINUSbeetle.addEventListener(MouseEvent.CLICK,doMINUSbeetle);
function doMINUSbeetle (e){
var myBeetle = new beetleBug();
myBeetle.parent.removeChild(myBeetle);
}
Please help. Thanks.
you're losing your myBeetle reference whenever you add one. and because it looks like you can add more than one before removing, you need some way to maintain references to them all. one way to do that is to use an array to store your references.
...
var beetleA:Array=[]; function randRange(startNum, endNum) {
return Math.floor(startNum +(Math.random()
* (endNum - startNum)));
}var myBeetle = new beetleBug();
beetleA.push(myBeele);
btnADDbeetle.addEventListener(MouseEvent.CLIC
Copy link to clipboard
Copied
you're losing your myBeetle reference whenever you add one. and because it looks like you can add more than one before removing, you need some way to maintain references to them all. one way to do that is to use an array to store your references.
var beetleA:Array=[]; function randRange(startNum, endNum) {
return Math.floor(startNum +(Math.random()
* (endNum - startNum)));
}var myBeetle = new beetleBug();
beetleA.push(myBeele);
btnADDbeetle.addEventListener(MouseEvent.CLICK,doADDbeetle);
function doADDbeetle(e){
var myBeetle = new beetleBug();beetleA.push(myBeetle);
myBeetle.x = randRange(0, 800);
myBeetle.y = randRange(0, 800);
addChild(myBeetle);}
btnMINUSbeetle.addEventListener(MouseEvent.CLICK,doMINUSbeetle);
function doMINUSbeetle (e){
var myBeetle = beetleA.pop();
myBeetle.parent.removeChild(myBeetle);
}Please help. Thanks.
Copy link to clipboard
Copied
Thank you very much for your help! It works perfectly! Is there any method to do this without using array? I looked up on the internet and some people said something about DisplayObjectContainer and something about removing it from the parent. Sorry I'm still new to as3.0 so I'm not that sure. Looking forward to your reply. Thanks again!
Copy link to clipboard
Copied
yes, in addition to an array, there are other ways to maintain references including
1. assigning instance names to your objects,
2. using unique references to your objects,
3. assigning to a parent that contains no other children other than the ones you want to remove,
4. assigning some property to your objects that no other objects have,
5. and there probably more.
Find more inspiration, events, and resources on the new Adobe Community
Explore Now