Actionscript how to get name of instance using get

2019-08-28 01:05发布

问题:

Okay so I have a MovieClip called sC and need to write a code where, if you click the button (sC) then sC will dissapear. The function needs to work for multiple buttons. What I tried was

sC.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:MouseEvent):void {
    var self;
    self = MovieClip(getChildByName(event.target.name));
    self.visible=false;

Now when I try this code, it gives me an error when I click sC. It says "cannot access a property or method of a null object reference.". when I try to trace(self) it outputs "null". Is there a way where I can get the name of the instance of the object which is using the clicKHandler function and then make it's visibilty equal to false (visible=false)?

Note that when I trace(event.target.name) it says "instance127".

回答1:

In your code, the variable self resolves to your movieClip's name, but not the complete path to where it exists. Try setting it up like below, where target is the button that was clicked:

sC.addEventListener(MouseEvent.CLICK, clickHandler);

function clickHandler(event:MouseEvent):void
{
    event.target.visible = false;
}