How To: Access properties of MovieClip/Sprite/DisplayObject instances from within a class in ActionScript 3

When it comes to programming, the devil is always in the details. In this case, I just wanted to add a MovieClip to the stage in a flash file, and then access that MovieClip’s instance properties to control some other instance stuff from within a class. Sounds simple, right? But could I do it? Could I ****. If you’re reading this, then there’s a good chance you’re in the same boat. Luckily for us both, it’s not too difficult to do at all. Here’s some simple proof of concept code to help you along:

Note: This first example uses a class called Ball. If you want to see it in action either download my pre-made code (Adobe Flash CS4 format), or just draw a circle or something, select it, convert to symbol (shortcut key: F8), tick the “Export for ActionScript…” checkbox and give it a class name of “Ball” (capital B) then use the following code to access instance properties of a given Ball object from within the class itself.

Main Flash File (.fla) Code

Ball.as ActionScript File Code

The trick is that we keep a reference to (or really a copy of) the main flash file’s stage handy by passing it into the constructor, so we can refer to it and get at any instances of anything on that stage to work with. Also, if we’re getting an instance by name, then we have to set the .name property! I thought you could just get it by the instance name itself (as in, the variables own name, not it’s .name property), but apparently not.

You might wonder why go to all this effort when we could just call this.x instead of ballStage.getChildByName(“SOME_NAMED_DISPLAYOBJECT”) or such in the above code, but the reason is that by jumping through these extra hoops we can access the properties of instances of other classes inside any other class. For example, if I had a Football class and a Player class, I could access the properties of a Football instance on the stage from within the Player class, or vice-versa.

To show a more concrete example, try using the cursor keys to move the attractor (just an instance of a MovieClip on the stage) around the below – the particles interact with the location of the attractor MovieClip, because I grab a copy of it by name (which is slower than by index from what I read, but this is just an example) and then move each particle instance from that information in the Particle class:

Full source for the above keyboard attraction example can be found: here.

Cheers!

2 thoughts on “How To: Access properties of MovieClip/Sprite/DisplayObject instances from within a class in ActionScript 3”

Leave a Reply

Your email address will not be published.