MovieClip(root) Not working. How to access root variable from movieclip? Flash AS3

家住魔仙堡 提交于 2019-12-19 04:38:15

问题


Ok Ive got a simple flash file, since im trying to accomplish accessing a variable from the main stage inside a movie clip. All the things Ive found from google point to MovieClip(root). But its not working for me.

On the main timeline:

var MyName:String;
MyName = "kenny";

Then I have a movieclip called MyBox, its code:

trace(MovieClip(root).MyName);

And I get this error: TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::Stage@2d2df089 to flash.display.MovieClip. at MyBox/sendpmtext()

I have also tried MovieClip(parent), MovieClip(parent.parent), MovieClip(stage), MovieClip(this.stage) and no luck. Any help please?


回答1:


You could just do

parent["MyName"];

OR, a proper casting of the main timeline (in your context, the parent is of type MainTimeline):

MainTimeline(parent).MyName;

Parent is always a DisplayObjectContainer, which has no special properties you create. If you create custom properties, then you need to cast to the class that has those custom properties before you'll be able to access them by name. (the compiler otherwise doesn't know they exist, and gives you that error).

root refers to the topmost stage of your swf. Your main timeline is actually a child of stage, so vars/objects/methods on the main timeline are not a part of stage


If your using stage.addChild(MyBox), then stage is the parent, and not the main timeline. If for some reason you need to have stage as the parent, then you'd have to keep a reference to the mainTimeline somewhere you can access. You could create a var to do this in your MyBox timeline.

var mainTimeline:MainTimeline;

Then in the main timeline code, do this:

MyBox.mainTimeline = this;

Then you can access your var within MyBox by doing mainTimeline.MyName;




回答2:


Stage is DisplayObject, but not MovieClip. Try to use coercion

DisplayObject(stage)

or

DisplayObjectContainer(stage)

and to access custom properties:

DisplayObject(this)["MyName"]


来源:https://stackoverflow.com/questions/12589904/moviecliproot-not-working-how-to-access-root-variable-from-movieclip-flash-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!