Home > actionscript > AS3 finding your inner child

AS3 finding your inner child

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.

Advertisements
Categories: actionscript
  1. July 1, 2013 at 10:06 am

    It’s very straightforward to find out any matter on net as compared to books, as I found this article at this website.

  2. m88
    September 15, 2014 at 8:52 am

    Everyone loves what you uys are up too. This sort of clever wolrk and
    exposure! Keeep up the superb works guys I’ve incorporated you guys to my perfsonal blogroll.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: