Home > OS >  AS3 Dynamic Movie Clip name as variable
AS3 Dynamic Movie Clip name as variable

Time:09-17

In Animate CC I can add MovieClips from the library dynamically using the following code:

var MovieClipName_mc:MovieClipFromLibrary = new MovieClipFromLibrary();
stage.addChild(MovieClipName_mc);

I want to change the MovieClip I am adding on the fly so I need to have "MovieClipFromLibrary" as a variable. However, I can't seem to get anything to work.

I hope I've explained that correctly? Help greatly appreciated. Thanks!

CodePudding user response:

Something like getDefinitionByName(...) method should work.

//# setup the vars
var myVar :String = "MovieClipFromLibrary";
var MovieClipName_mc :Class;

//# apply the vars and add to screen
MovieClipName_mc = getDefinitionByName( myVar ) as Class;
stage.addChild(MovieClipName_mc);

You could also make a function createInstance to take care of adding multiple vars like below:

Implementation:

import flash.utils.getDefinitionByName;

function createInstance(avalue:*):*
{
    var C:Class;
    
    if (avalue is Class)
    {
        C = avalue as Class;
    }
    else if (avalue is String)
    {
        // If there is actually a class in library
        // with the provided class name, then
        // C will be filled with a valid class.
        C = getDefinitionByName(aname) as Class;
    }
    
    if (C != null)
    {
        return new C;
    }
    else
    {
        return null;
    }
}

Usage:

var M:DisplayObject;

// Pass class name as String.
M = createInstance("MovieClipFromLibrary");

if (M != null)
{
    stage.addChild(M);
}

// Pass class reference as is.
M = createInstance(MovieClipFromLibrary);

if (M != null)
{
    stage.addChild(M);
}

Please keep in mind that you can access only the classes of the current SWF this way. If you want it to obtain things from loaded SWFs, you will need to set up some kind of library manager and get things via Loader.contentLoaderInfo.applicationDomain.getDefinition(...) method.

CodePudding user response:

That exact code didn't work for me. It gave me an implicit coercion error. However, it was super helpful because this did work...

    //Get Item from library
    var MCName:Class = getDefinitionByName('TEST') as Class;
    
    var MovieClip_mc:MovieClip = new MCName();
    stage.addChild(MovieClip_mc);

So thanks a lot!!

  • Related