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

actionscript-3flash

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?

Best Answer

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;

Related Topic