开发者

Cannot create an object through actionscript

开发者 https://www.devze.com 2023-04-10 06:38 出处:网络
I开发者_StackOverflow 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 m

I开发者_StackOverflow 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...?!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消