Do you like my tutorials?

Then consider supporting me on Ko-fi

Talking about Actionscript 3 and Flash.

You are about to meet an event that is not used as it would deserve, because – sad but true – programmers do not use it that much.

Let me give ADDED_TO_STAGE event its moment of fortune and fame, and you will never ever live without it.

First, let me say the event is triggered when an object is added to stage, that is when you execute an addChild, this way:

addChild(my_mc);

When the object is successfully placed on the stage, Event.ADDED_TO_STAGE event will be fired.

Ok, but what’s the point?

Well, in AS3, things that have access to stage are not on stage unless you put them there using addChild.

So a script like this

var my_obj:a_class= new a_class();
addChild(my_obj)

will initialize the my_obj object before it’s physically placed on the stage.

So any line of code inside the a_class function inside the a_class class will be executed before my_obj is on the stage.

What’s the point?

Let’s see this script:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class ats_example extends Sprite {
		public function ats_example() {
			var child:a_child = new a_child();
			addChild(child);
		}
	}
}

where a_child.as is:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class a_child extends Sprite {
		public function a_child() {
			trace("this is the stage: "+stage);
			trace("this is my parent: "+this.parent);
		}
	}
}

The output is:

this is the stage: null
this is my parent: null

and this can draw you mad, thinking about an AS3 bug… but it’s just a malpractice.

Try this one instead:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class a_child extends Sprite {
		public function a_child() {
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		function init(e:Event):void {
			trace("this is the stage: "+stage);
			trace("this is my parent: "+this.parent);
		}
	}
}

and you will see the light:

this is the stage: [object Stage]
this is my parent: [object ats_example]

I admit it… I lost an hour of my life trying to understand those null values…

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.