Archive

Archive for June, 2007

AS3 finding your inner child

June 15, 2007 2 comments

Been spending the last hour trying to figure out how AS3 nests child DisplayObjects. All the documentation works nice and good if you are not nesting movieclips… but who doesn’t nest movieclips? It would have been nice if there was some kind of findChild(‘childname’) function that would live in the DisplayObjectContainer and just traverse the tree and give you back what you’re looking for. In the absence of such a method, of course, you come up with one of your own:

function makeStack(container:DisplayObjectContainer):Array {
 var a:Array = new Array();
 for(var i:int=0; i < container.numChildren;i++)
 {
 	var child:DisplayObject = container.getChildAt(i);
 	a.push(child);
 }
 return a;
}
function findChild(container:DisplayObjectContainer, p_name:String):DisplayObject
{
 var child:DisplayObject;
 var stack:Array = makeStack(container);

while(stack.length) {
 	child = stack.pop();
 	if (child.name == p_name)
 	{
 		break;
 	}
 	if (child is DisplayObjectContainer)
 	{

 		var a:Array = makeStack(DisplayObjectContainer(child));

 		for(var j:int=0;j < a.length;j++)
 		{
 			stack.push(a[j]);
 		}
 	}

 }

 return child;

}

The basic usage would be: findChild(this, ‘some_deeply_nested_clip_instance_name’);

One annoying thing is that the array.concat was not merging the two arrays… so the code got a little ugly.

Categories: actionscript