0

I created MovieClip, "Exported it for ActionScript" with the same name. It's okay when I create an object visually, by dragging it to the stage but when using var smth:* = new myClass() an error occurs. There is an error because I have some code in the MovieClip I exported, and it involves the Stage. It happens so that stage is not instantiated at the moment of running code? I mean, I'm creating the object on the second frame so it's seems kinda impossible. When (in the MovieClip) I write trace(stage); output is null. As I said, there is no problem when creating object visually. Ladies and gentlemen, what the...?!

2 Answers 2

1

If I follow what you're saying, you don't have a reference to the stage right-away inside your MovieClip subclass? This happens if the MovieClip is not attached to the stage or another DisplayObjectContainer that is already attached to it (somewhere up the Display-list chain).

One way to verify if the stage is available AND to execute your code WHEN IT IS available, is a little code snippet often found in FlashDevelop projects:

public function Main():void {
    stage ? init() : addEventListener(Event.ADDED_TO_STAGE, init);
}

private function init(e:Event = null):void {
    removeEventListener(Event.ADDED_TO_STAGE, init);
    // entry point
}

So if the stage IS found, it immediatly triggers the init() method (without arguments), otherwise it will wait for when it is added to the stage (or some other DisplayObjectContainer that is already attached), which will pass in the Event parameter when it makes use of init(e:Event) as a callback method.

Sign up to request clarification or add additional context in comments.

Comments

1
import flash.events.Event;

In the constructor of the class add an eventListener for the stage to be added.

this.addEventListener(Event.ADDED_TO_STAGE, myFunction);

then just create an eventListener with the name init and with an event as parameter.

function myFunction(e : Event) : void
{
    this.removeEventListener(Event.ADDED_TO_STAGE, myFunction);

    // execute code here
}

The removeEventListener is required, don't forget to remove it! A bug in flash will trigger the event added to stage twice, so if you don't want to execute the code twice, you have to remove it.

2 Comments

oh, thanks. it works. however, whenever i write MovieClip(this.root) there is an error which says that AS was not able to convert Stage to MovieClip. Why is that?
Please ask this in a separate question, that way others users can find the solution faster using search :-).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.