Posted by: Yogesh Puri on: September 26, 2008
The post contains a solution for a case where you need to attach a Library symbol and you have to pass that class name as a string to the function.
The approach followed here is by using the getDefinitionByName utility which interprets the string and convert it into a Class. Then you can use a new syntax with that particular class. Following is a code for the same solution and you can download the source files from here. The “testMC” here is a movieClip in library with the className as testMC and BaseClass as flash.display.MovieClip
import flash.utils.getDefinitionByName;
function addMovieFromLibrary(mcIName:String){
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
addChild(newMc);
}
addMovieFromLibrary("testMC");
[...] Attaching MovieClip from library by passing classname as a string in function in AS3 [...]
That’s what I mean but a little different. here is what I was working on but it outputs an error. maybe you can help me figure out why this doesn’t work.
Thank you
stop();
import flash.utils.getDefinitionByName;
function addMovieFromLibrary(mcIName:String){
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
addChild(newMc);
}
function removeChildWithRef(mcIName:String, parentObj:*){
var t:DisplayObject = parentObj.getChildByName(mcIName);
parentObj.removeChild(t);
}
home_btn.addEventListener(MouseEvent.CLICK, buttonHome);
function buttonHome(event:MouseEvent):void {
gotoAndPlay(”home”);
removeChildWithRef(”audio_mc”,this);
trace(”unloaded audioProof”);
}
one_btn.addEventListener(MouseEvent.CLICK, buttonOne);
function buttonOne(event:MouseEvent):void {
gotoAndPlay(”one”);
addMovieFromLibrary(”audio_mc”);
trace(”loaded audioProof”);
}
OUTPUT
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/removeChild()
at test_movie_fla::test_mc_1/removeChildWithRef()
at test_movie_fla::test_mc_1/buttonHome()
Yo Yogi man,
How are you? Remember me!!! Where are you these days?
Came across this blog as I was looking for something similar. But, I want to add the library item inside a Sprite on Stage and not at root level. How easy is it?
Speak soon.
Cheers!
Cool mate! I will get it working…..Thanks..Chat soon on gTalk!
Just what I needed!
And simple code with no extra bull too.
Thanks!
Thank you so much… this WAS VARY HELPFUL!!!!!!!!!!
[...] See the original post: Attaching MovieClip from library by passing classname as a string in function in AS3 [...]
October 20, 2008 at 9:23 pm
Do you have a removeChild Function too?