getDefinitionByName

Imagine you have a .swc file that contains objects named from "mcObj0" to "mcObj11", and want to add those objects randomly to the screen. One way to do this would be:

A better approach is one that uses 'getDefinitionByName'. This method allows to create objects dinamically and results in less code written. That means we could refactor the above code into:

Look ma, only three lines, that's great! To use this method you also have to remember to add the compiler parameter "-include-libraries". Here is how to do it:

- In the project properties choose "ActionScript Compiler"

- On the "Additional compiler arguments" field add the following:

-include-libraries PATH_TO_SWC

The path should be the absolute path, relative won't work.

4 Responses to “getDefinitionByName”

  1. sdgdg Says:

    张家界旅游

  2. iestyn lloyd Says:

    Hey, thanks for this, I was wondering WTF was going on for a while :)

    FYI, I got a relative path working. If you’re using FlashDevelop (3.0.0 Beta9), it needs to be relative to your .as3proj file.
    This worked: -include-libraries dev\swc\videos.swc

  3. Dan Says:

    Hi,

    I have something similar to this, all though not the same, I have no experience with SWC files.

    I have defined 3 MovieClips:

    var man1DR:MovieClip = new MovieClip();
    var man1UL:MovieClip = new MovieClip();
    var man1UR:MovieClip = new MovieClip();

    I want to add one of these to a movieClip as a child, depending on a variable ‘dir’.

    “man1″ + dir gives me the name of one of those 3 movieClips, but if I do:

    object.addChild(”man1″+ dir);

    I get an error as it is a string and not the actual movieClip. Do you know how I fix this??

  4. Dan Says:

    If I do this:

    var man:Class = getDefinitionByName(”man1″ + dir) as Class;
    var obj = new man() as DisplayObject;
    object.removeChildAt(0);
    object.addChild(obj);

    I get this error:

    ReferenceError: Error #1065: Variable man1UR is not defined.

    When, as you can see above, it is defined…?

Leave a Reply