Showing posts with label Simple Way to AttachMovie for ActionScript 3.0 (AS3) add child. Show all posts
Showing posts with label Simple Way to AttachMovie for ActionScript 3.0 (AS3) add child. Show all posts

Saturday, January 8, 2011

Simple Way to AttachMovie for ActionScript 3.0 (AS3)

If you want to attach movie clip from library to stage in AS3, you should use addChild function. But I prefer the AS2 way to do that, which is called attachMovie.
And also, to remove a movie clip, you can use my AS2-like function to do that.
Here is a function to attach movie and remove movie in AS3 :


function myRemoveMovieClip(target){
if(target != null){
var parent1 = target.parent;
var instance = target.name;
if(parent1.getChildByName(instance) != null){
parent1.removeChild(parent1.getChildByName(instance));
target = null;
}
}
}



function myAttachMovie(tempMov:MovieClip,instance:String,parent1:MovieClip,pos:Object){
if(parent1.getChildByName(instance) != null){
myRemoveMovieClip(parent1.getChildByName(instance));
}
tempMov.name = instance;
parent1.addChild(tempMov);
for(var i in pos){
tempMov[i] = pos[i];
}
return tempMov;
}


Here is an example to use those functions :

myAttachMovie(new linkageNameInLibrary(), "instanceNameYouWant", MovieClip(root), {x:250, y:90});
myRemoveMovieClip(MovieClip(root).getChildByName("instanceNameYouWant"));

Note :
In AS3, to access an instance of movieClip/button in stage, which you attached using code, you must use getChildByName like above example.
If not attached using code, I mean if you place a movieClip/button directly and give it an instance name, you must access it like this : MovieClip(root).instanceNameYouWant