A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: new [var];

  1. #1
    Senior Member
    Join Date
    Apr 2005
    Location
    FL, USA
    Posts
    442

    new [var];

    A stupid question I'm sure, but here goes:

    I have a MC with class name "House" in the library.
    The Build function will be used to add hundreds of different MCs to the stage, so I am using the the argument "unit".
    Code:
    function Build(unit:String) {
    var newUnit:MovieClip = new unit;
    addChild(newUnit);
    }
    Build("House");
    The problem I seem to be getting is that "new unit;" is literally looking for the class "unit" rather than evaluating the variable. How can I force the evaluation of "unit"?

  2. #2
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    You need to use getDefinitionByName to get a Class object from your String argument.

    Then, please use () in the new call. Although not strictly necessary for classes with no argument constructors, it makes it obvious that you are calling the constructor function.

    Code:
    import flash.utils.getDefinitionByName;
    
    function Build(unit:String) {
      var clazz:Class = getDefinitionByName(unit);
      var newUnit:MovieClip = new clazz();
      addChild(newUnit);
    }
    Build("House");

  3. #3
    Senior Member
    Join Date
    Apr 2005
    Location
    FL, USA
    Posts
    442
    Code:
    function Build(unit:String) {
    var clazz:Object = getDefinitionByName(unit);
    var newUnit:MovieClip = new clazz();
    addChild(newUnit);
    }
    Build("House");
    Ended up having to data type it as an Object to get the MC on the stage, but getDefinitionByName() is indeed what I was looking for.

    Thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center