public class MyClass extends MovieClip {
public function MyClass():void {
my_mc.addEventListener(MouseEvent.CLICK, action);
}
private function action(e:MouseEvent):void {
trace("cliked");
}
}
时间轴代码
var myClass:MyClass = new MyClass();
addChild(myClass);
我无法访问my_mc
(放置在FLA中)动画片段。我如何访问?
答案 0 :(得分:7)
试试这个:
public class MyClass extends MovieClip
{
public function MyClass()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var myMc:MovieClip = stage.getChildByName("my_mc") as MovieClip;
// var myMc:MovieClip = parent.getChildByName("my_mc") as MovieClip;
myMc.addEventListener(MouseEvent.CLICK, onMyMcClick)
}// end function
private function onMyMcClick(e:MouseEvent)
{
trace("clicked");
}// end function
}// end class
如果这不起作用(我认为不会这样),那是因为你的my_mc
显示对象不是舞台的子节点,而是{{1}的实例的子节点}。如果是这样,那么只需在上面的代码中注释掉以下语句:
MainTimeline
并在上面的代码中取消注释以下语句:
var myMc:MovieClip = stage.getChildByName("my_mc") as MovieClip;
如果我的假设是正确的,// var myMc:MovieClip = parent.getChildByName("my_mc") as MovieClip;
和my_mc
显示对象共享同一个父级。
答案 1 :(得分:0)
如果my_mc
是MyClass舞台上的MovieClip,您可能会过早地尝试访问它。构造函数代码通常在绘制第一帧之前执行,因此您需要通过监听Event.ADDED_TO_STAGE
来等待该绘图:
public class MyClass extends MovieClip {
public function MyClass():void {
if(stage) {
init();
} else {
addEventListener(Event.ADDED_TO_STAGE,init);
}
}
private function init(e:Event = null):void {
if(e) removeEventListener(Event.ADDED_TO_STAGE,init);
stage.my_mc.addEventListener(MouseEvent.CLICK, action);
}
private function action(e:MouseEvent):void {
trace("cliked");
}
}