Kevin McGowan
Kevin McGowan

Reputation: 463

Dyanmically creating an instance of a class in AS3 (not in Library)

I'm trying to create an instance of a class based on the variable sent to me from the function initiation.

This class is not a displayObject and is not in the Flash library. This seems to mean that the following does not work:

private function BasicControl(_stage:int):void {
        var s1:tut_stage = getDefinitionByName("stage"+_stage) as tut_stage;
        trace(s1);
        s1.Begin();
    }

This results in:

ReferenceError: Error #1065: Variable stage1 is not defined.
at global/flash.utils::getDefinitionByName()
at kazo::Main/BasicControl()[B:\Users\Kevin SSD\client\temp_tutorial\preview_src\kazo\Main.as:76]
at kazo::Main/SWFLoadComplete()[B:\Users\Kevin SSD\client\temp_tutorial\preview_src\kazo\Main.as:113]

However, if it is written as:

var s1:tut_stage = new stage1;

This will work fine.

How does one go about dynamically calling a class if it is not in the library? It seems that all of my efforts are returning no results. The only way that I can get this to work is using a horrible work around:

private function BasicControl(_stage:int):void {
        var s1:tut_stage;

        switch(_stage) {
            case 1:
                s1 = new stage1;
                break;

            case 2:
                s2 = new stage2;
                break;

        }
    }

I must be missing something here - How should I be calling stage1 in this instance?

Upvotes: 0

Views: 179

Answers (1)

Alexis King
Alexis King

Reputation: 43902

The getDefinitionByName function returns a class reference. Try this instead:

var Clazz:Class = getDefinitionByName("stage" + _stage) as Class;
var s1:tut_stage = new Clazz() as tut_stage;

Additionally, you have to ensure that your classes are being included in the SWF at compile-time. Just reference them somewhere to force Flash to include them.

stage1; stage2;

You'll need to add references for any classes you want to include, but you'll only have to do this once.

Upvotes: 1

Related Questions