Wednesday, August 15, 2007

ActionScript 3 access movie clips like you did in AS2

So the old way of getting to movieclips was kind of nice, you could just use there name and drill through things. There is now in AS3 a separation between classes and displayobjects so now you can use the dot syntax on class instances like so... this.class1.class2.class3 but you can't do the same with movie clips like you could... _root.mc1.mc2.mc3 you have to this.getChildByName("mc1").getChildByName("mc2").getChildByName("mc");

Personally I think this isn't as great so I made this.

Use it something like this.
var mc:DisplayObject = getElement("this.parent.myClip.childClip.childClip2", this);


public function getElement( path:String,
thisElement:DisplayObjectContainer = null ) : DisplayObject {
var pathArray:Array = path.split(".");
var baseElement:*;

if( pathArray[0] == "root" ) baseElement = target;
else if( pathArray[0] == "this" ) baseElement = thisElement;
else if( pathArray[0] == "parent" ) baseElement = thisElement.parent;

var pathObject:* = baseElement;
var currentPart:int = 1;
loop();
function loop() : void {
if( currentPart != pathArray.length ){
if( pathArray[0] == "parent" ) pathObject = pathObject.parent;
else pathObject = pathObject.getChildByName( pathArray[currentPart++] );
loop();
}
}
return pathObject;
}


I was thinking adding nextSibling type calls might be nice also but this does what I wanted for now.

Labels: ,

2 Comments:

Blogger Gromek said...

Fine idea. But what is target variable?

1:04 AM  
Blogger tyler said...

target is simply a reference to root which you will have to know within your application. If you put this method in your document class it would be "this"

7:38 AM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home