Trying to make buttons on actionscript: create and remove movieclip object, but always some errors... I need one button creates movieclip, another must to delete it by mouse click. Here is code:
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.text.TextField;
main.addEventListener(MouseEvent.CLICK, addMain);
function addMain(e: MouseEvent) {
var movieClip: bm = new bm();
movieClip.x = 640;
movieClip.y = 570;
this.addChild(movieClip);
main.removeEventListener(MouseEvent.CLICK, addMain);
deletemain.removeEventListener(MouseEvent.CLICK, addMain);
}
deletemain.addEventListener(MouseEvent.CLICK, deleteMain);
function deleteMain(e: MouseEvent) {
var movieClip: bm = bm(event.target);
this.removeChild(movieClip);
removeChild(movieClip);
movieClip = null;
deletemain.removeEventListener(MouseEvent.CLICK, deleteMain);
}
OK, to understand why your code is not working, let's take a look on it :
main.addEventListener(MouseEvent.CLICK, addMain);
function addMain(e: MouseEvent)
{
// here you are creating a local var "movieClip"
// inside your "addMain" function, so it's only accessible here
var movieClip:bm = new bm();
movieClip.x = 640;
movieClip.y = 570;
this.addChild(movieClip);
main.removeEventListener(MouseEvent.CLICK, addMain);
// I don't really know why you do this !
deletemain.removeEventListener(MouseEvent.CLICK, addMain);
}
deletemain.addEventListener(MouseEvent.CLICK, deleteMain);
function deleteMain(e: MouseEvent)
{
// here, you are creating a local var "movieClip"
// by casting (converting) your "deletemain" button (e.target) to an "bm" object
// event.target should be e.target
var movieClip: bm = bm(event.target);
// here your are removing the "deletemain" button, once
this.removeChild(movieClip);
// and twice
removeChild(movieClip);
movieClip = null;
deletemain.removeEventListener(MouseEvent.CLICK, deleteMain);
}
So to do what you want : creating a MovieClip and removing it using two buttons, you have to declare your "movieClip" as a global var to be accessible for your two listener functions :
// declare a global "bm" object
var movieClip:bm;
btn_add.addEventListener(MouseEvent.CLICK, btn_add_onPress);
function btn_add_onPress(e: MouseEvent): void
{
// create the "movieClip" object
movieClip = new bm();
addChild(movieClip);
// remove the click event listener for the btn_add
btn_add.removeEventListener(MouseEvent.CLICK, btn_add_onPress);
}
btn_delete.addEventListener(MouseEvent.CLICK, btn_delete_onPress);
function btn_delete_onPress(e:MouseEvent) : void
{
// remove the "movieClip" object
removeChild(movieClip);
movieClip = null;
// remove the click event listener for the btn_delete
btn_delete.removeEventListener(MouseEvent.CLICK, btn_delete_onPress);
}
Hope that can help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.