Quick AS3 tip that may be self-explanatory to most of you out there, yet stumped me for a while. In AS2, if you set a variable on your main timeline and wanted to access it from inside a movieclip, all you would need to do is call it by name. AS2 would then proceed up the scope chain looking for the variable by name. First, inside the movieclip, then on the parent of the movieclip (in this case…stage).
AS3 is a little different. Say you declare a variable on your main timeline like so:
var my_arr:Array = ["one", "two", "three", "four"];
Then you place a movieclip on your stage, and INSIDE your movieclip, you want to reference
my_arr (which is on the main timeline, or the movieclip’s parent). Back in AS2, you would simply type out
my_arr, and Flash would automagically find the variable as it searched the scope chain. In AS3, however, if you type this (again…inside the movieclip):
trace (my_arr); or even
You would get this error:
1119: Access of possibly undefined property my_arr through a reference with static type flash.display:DisplayObjectContainer.
Well, to avoid this little annoyance, you can try a strict coercion like so:
I wish I knew the exact reason as to why this behavior exists, but I do have my suspicions and theories in case you’re interested. What I believe is happening is that in AS3, the movieclip doesn’t want to assume it knows what its parent is. In fact, as far as it’s concerned, it only worries about whatever is in it, or “below” it (the concept is called encapsulation). Anything outside of it (or “above” it) is basically anybody’s guess and unless you specifically tell it “your parent is a movieclip,” it doesn’t make any assumptions.
Again, that’s my own theory – so if anyone out there knows the real reasons for this behavior (or even a better way of handling this) – let us know!