dynamic loading images by name from library [duplicate] - actionscript-3

This question already has answers here:
Can I create an instance of a class from AS3 just knowing his name?
(2 answers)
Closed 7 years ago.
i have a small problem with loading specific images in flash...
In my project I want to load a certain image from the library (f.ex. "event1_pic.jpg") - the actual number is stored in an int variable.
I already exported the jpg for actionscript and it works fine when i directly call the image by its full name...
That's the current working solution (calling the full name of the image) :
var event_pic = new event1_pic();
bmp = new Bitmap(event_pic);
addChild(bmp);
My attempt on integrating the int variable in the name (event_number=1):
var event_pic = new this["event"+event_number+"_pic"]();
big_pic = "event"+event_number+"_pic";
var event_pic = new this.big_pic();
Can anyone please help me with that problem? Or maybe anyone knows another solution on loading specific images that only differ in name?

As mentioned in the comments, you can use flash.utils.getDefinitionByName() like this :
for(var i:int = 0; i < n; i++){
var mc:MovieClip = new (flash.utils.getDefinitionByName('my_class_' + i) as Class);
addChild(mc);
}
Or using loaderInfo.applicationDomain.getDefinition() :
for(var i:int = 0; i < n; i++){
var mc:MovieClip = new (this.loaderInfo.applicationDomain.getDefinition('my_class_' + i) as Class);
addChild(mc);
}
Hope that can help.

Related

problem accessing dynamic movieclips by name in adobe animate

I've done this a million time, but here it didn't work.
I have a game_mc inside a animate.fla. inside this clip I generate a view targetareas to place stones on it. ok, the TargetArea is a simple Movieclip inside my lib.
I can see everything, I can click on the area an get the propper name, I can get the names of the clips inside game_mc.
but I can't access it by using game_mc[clipname]
for (var i:int = 1; i<= 20; i++){
var targetArea:TargetArea = new TargetArea();
targetArea.txt.text = String(i);
var modu = ((i-1) %5);
targetArea.x = 100 + modu * 340;
var abs = int((i-1) / 5);
targetArea.name = "targetarea_" + String(i)+ "_mc";
targetArea.mouseChildren = false;
targetArea.y = 100 + (abs * 200) ;
game_mc.addChild(targetArea);
}
for(var x:int=0;x < game_mc.numChildren;x++) {
trace (game_mc.getChildAt(x).name);
}
for (var i:int = 1; i< 20; i++){
var targetName:String = "targetarea_" + i + "_mc"
trace( game_mc[targetName].x);
}
I think the name you assign your TargetArea instances isn't automatically converted
into a property of the DisplayObject you attach it to. As far as I remember though this
nonchalant way of accessing MovieClips using array access used to work prior to AS3.
The more elegant solution is to retrieve the child using getChildByName().
trace(game_mc.getChildByName(targetName).x);
Additionally, in case game_mc is an instance of MovieClip or a dynamic class you can make the TargetArea instances a property of it using:
game_mc[targetArea.name] = targetArea;
This way you can access them using game_mc[name].property afterwards.

send json data to array(movieclip) as3.0

I am building an air app in flash cs6 using as3. I need to send a json to movieclip. I wanted to create a "timeline" on my application.
This is the code I use.
function onCompleteLoadTimeline(event:Event){
var result:Object = JSON.parse(event.target.data);
var yPos = 0;
for (var h:int=0; h<=1; h++){
tpost = new t_post();
tpost.x = 0;
tpost.y = 0;
timeline_mc.addChild(tpost);
timeline_container.push(tpost);
timeline_container[h].y = yPos;
yPos += timeline_container[h].batas.y;
}
for (var i:Object in result){
for (var j:int=0; j<=1; j++){
timeline_container[j].nama.text = result[i].timeline_name;
timeline_container[j].postingan.text = result[i].timeline_post;
}
trace ("nama : "+result[i].timeline_name);
trace ("status : "+result[i].timeline_post);
trace ("waktu : "+result[i].date);
trace ("suka : "+result[i].likers);
}
}
for the code only the latest data appear in the movie clip.
please help me.
You have a few for loops that go up to 1. I don't know what they are for.
The only loop that you need is the one iterating over the result.
var result:Object = JSON.parse(event.target.data);
var yPos = 0;
for (var i:Object in result){
var tpost:t_post = new t_post();
tpost.y = yPos;
timeline_mc.addChild(tpost);
tpost.nama.text = result[i].timeline_name;
tpost.postingan.text = result[i].timeline_post;
yPos += tpost.height + 10;
}
I have no idea what batas means (use English in your code!) which is why I created the logic to position the objects myself. If yours worked for you, just use that.
I also omitted the array code for brevity.
Btw: You are essentially building a custom component with a custom way to display data which is often referred to as an "item renderer". Go ahead and search for that term if you don't want to build everything from scratch.

Can anyone help me change this code from AS2 to AS3

This will be a simple clock. I've been using AS2 since I learned Flash in early 2000s. It's time to move on.
for (a=1; a<60; a++) {
duplicateMovieClip("dot0", "dot"+a, 10+a);
_root["dot"+a]._rotation = a*6;
_root["dot"+a].gotoAndStop(1);
}
Adobe published ActionScript 2.0 Migration that helped me tremendously back in the day.
Some specifics related to your code:
Properties aren't prefixed with underscores, ex _rotation is now rotation, and _root is now root.
root is not global, it is a property of display objects, and it is null if the display object is not in the display list.
duplicateMovieClip does not exist anymore. You should export your symbol to a class and use new operator and addChild() to create an instance and add it to the display, ex:
var dot:Dot = new Dot();
addChild(dot);
Display objects created in code are not automatically given a name and assigned to a property on its parent when added to the display. You can set the name and use getChildByName on its parent. Example:
var dot:Dot = new Dot();
dot.name = "dot" + i;
addChild(dot);
var n:int = 10;
var dot10:Dot = getChildByName("dot" + n) as Dot;
But this is a bit cumbersome, so in most cases it makes more sense to just store your display objects in your own array and reference them by index:
var dots:Array = [];
var dot:Dot = new Dot();
addChild(dot);
dots.push(dot);
var firstDot:Dot = dots[0];
That should get you started.
Thanks to help here and elsewhere, this is what works for me:
var i:Number = 1;
var dots:Array = [];
for (i=0; i<60; i++) {
var dot:Dot = new Dot;
addChild(dot);
dots.push(dot);
dot.x=683;
dot.y=436;
dot.rotation = i*6;
dot.gotoAndStop(1);
}
The clock I'm making don't have hands but the dots change color for the hours minutes and seconds. Thanks everybody who helped

AS3 reference movieclip by .name property

Yay, another simple noobie as3 question.
How can I reference a movieclip by its ".name" ?
I tried searching for a solution, but I couldn't find anything. Basically I have a set of movieclips added to the stage using a loop, so the way I found to diferentiate them was by giving them a .name of "something" + the Loop's "i". So now they are named something like "something1", "something2", "something3", and so on.
Now, I need to send some to a specific frame. Usually I would do something like:
something1.gotoAndStop(2);
But "something1" isnt the instance name, just the ".name". I cant find a way to reference it.
you want to use getChildByName("name") more info
import flash.display.MovieClip;
// create boxes
for(var i:int = 0 ; i < 4; i++){
var box:MovieClip = new myBox(); // myBox is a symbol in the library (export for actionscript is checked and class name is myBox
box.name = "box_" + i;
box.x = i * 100;
this.addChild(box);
}
// call one of the boxes
var targetBox:MovieClip = this.getChildByName("box_2") as MovieClip;
targetBox.gotoAndStop(2);
Accessing things by name is very prone to errors. It's not a good habit to get into if you're a newbie. I think a safer way to do this would be to store references to the things you're creating in the loop, for example in an array, and reference them by their indexes.
Example:
var boxes:Array = [];
const NUM_BOXES:int = 4;
const SPACING:int = 100;
// create boxes
for(var i:int = 0 ; i < NUM_BOXES:; i++){
var box:MovieClip = new MovieClip();
// You can still do this, but only as a label, don't rely on it for finding the box later!
box.name = "box_" + i;
box.x = i * SPACING;
addChild(box);
// store the box for lookup later.
boxes.push(box); // or boxes[i] = box;
}
// talk to the third box
const RESET_FRAME:int = 2;
var targetBox:MovieClip = boxes[2] as MovieClip;
targetBox.gotoAndStop(RESET_FRAME);
Note, I've also replaced many of the loose numbers with constants and vars which will also help your compiler notice errors.
You can use the parent to get the child by name. If the parent is the stage:
var something1:MovieClip = stage.getChildByName("something1");
something1.gotoAndStop(2);

Add multiple movieclips, not replacing the old ones

So, in short, my problem is this. I am using a variable which is a movieclip loaded from an external swf. I want to "spawn" multiple instances of the movieclip that all react to the same code, so for example if I say var1.x = 100, they all are at 100x. But my problem is when I run addChild(var1) multiple times(I'm not actually typing in addChild(var1) over and over, I just have it set to add them at random times), the new child just replaces the old one, instead of making multiple movieclips. Should I do something like
var var1:MovieClip
var var2:MovieClip = new var1 ?(which doesnt work for me btw, gives me errors)
Oh, heres the code, and also, I am pretty new to as3 fyi, still don't even know how arrays work, which was my second guess to the problem.
var zombieExt:MovieClip;
var ldr2:Loader = new Loader();
ldr2.contentLoaderInfo.addEventListener(Event.COMPLETE, swfLoaded2);
ldr2.load(new URLRequest("ZombieSource.swf"));
function swfLoaded2(event:Event):void
{
zombieExt = MovieClip(ldr2.contentLoaderInfo.content);
ldr2.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfLoaded2);
//zombieExt.addEventListener(Event.ENTER_FRAME, moveZombie)
zombieExt.addEventListener(Event.ENTER_FRAME,rotate2);
function rotate2 (event:Event)
{
var the2X:int = playerExt.x - zombieExt.x;
var the2Y:int = (playerExt.y - zombieExt.y) * 1;
var angle = Math.atan(the2Y/the2X)/(Math.PI/180);
if (the2X<0) {
angle += 180;
}
if (the2X>=0 && the2Y<0) {
angle += 360;
}
//angletext.text = angle;
zombieExt.rotation = (angle*1) + 90;
}
playerExt.addEventListener(Event.ENTER_FRAME,spawn1);
function spawn1 (event:Event)
{
if(playerExt.y < 417)
{
var someNum:Number = Math.round(Math.random()*20);
if(someNum == 20)
{
addChild(zombieExt)
zombieExt.x = Math.round(Math.random()*100)
zombieExt.y = Math.round(Math.random()*100)
}
}
}
}
addChild() does not create new instances. It is used to add an already created instance to the display list. If you call addChild() multiple times on the same instance then you are just readding itself.
Also each instance is unique, you can not globally change the x position of an instance by changing another one of them. What you would do is as Henry suggests and add each new instance of a MovieClip into an array, then whenever you change something you can loop through the array and apply the changes to each instance.
You can not go var2:MovieClip = new var1 either since var1 is an instance and not a class.
Here's a different method of receiving loaded MovieClips, which i use when i need many copies of the item.
in the swf you are loading, give the target movieclip a linkage name in the library, for this example i will use "foo"
private var loadedSwfClass:Class
private var newZombie:MovieClip;
private var zombieArray:Array = new Array();
function swfLoaded2(event:Event):void
{
loadedSwfClass = event.target.applicationDomain.getDefinition("foo");
for(var n:int = 0; n<100; n++){
newZombie = new loadedSwfClass()
zombieArray.push(newZombie);
addChild(newZombie);
}
}
as per this tutorial
http://darylteo.com/blog/2007/11/16/abstracting-assets-from-actionscript-in-as30-asset-libraries/
although the comments say that
var dClip:MovieClip = this;
var new_mc = new dClip.constructor();
this.addChild(new_mc);
will also work.
It sounds like you might be accessing the same instance some how in your code. It would be helpful to see your code to figure this one out.
If I wanted to load in one swf files and add a MovieClip multiple times I would place it in the library of that SWF file. And then instantiate it and store it into an object pool or a hash or some list.
// after the library were finished loading
var list:Array = [];
for(var i:int=0; i<10; i++) {
var myCreation:MySpecialThing = new MySpecialThing();
addChild(myCreation);
list.push(myCreation);
}
where my library would contain a linkage to the class MySpecialThing.
Calling addChild(var1) multiple times on the same parent doesn't have any effect (unless you have added another child to the same parent in between, in which case it will change the child index and bring var1 to the top). If you call it on different parents, it will just change the parent of var1, doesn't duplicate. Call addChild(new MovieClassName()) at random times instead to add new copies of it. Use an array as suggested here to access them later.
Wow, thanks there henry, just using an array did exactly what I needed, and made things alot simpler.
when you load in using a loader you only get 1 instance, however you can do some funky reflection to determine what class type the given loader.content is, and then instantiate them using that. For Example:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_completeHandler);
loader.load(new URLRequest("ZombieSource.swf"));
var classType:Class;
function loader_completeHandler(evt:Event):void
{
var loadInfo:LoaderInfo = (evt.target as LoaderInfo);
var loadedInstance:DisplayObject = loadInfo.content;
// getQualifiedClassName() is a top-level function, like trace()
var nameStr:String = getQualifiedClassName(loadedInstance);
if( loadInfo.applicationDomain.hasDefinition(nameStr) )
{
classType = loadInfo.applicationDomain.getDefinition(nameStr) as Class;
init();
}
else
{
//could not extract the class
}
}
function init():void
{
// to make a new instance of the ZombieMovie object, you create it
// directly from the classType variable
var i:int = 0;
while(i < 10)
{
var newZombie:DisplayObject = new classType();
// your code here
newZombie.x = stage.stageWidth * Math.random();
newZombie.x = stage.stageHeight * Math.random();
i++;
}
}
Any problems let me know, hope this helps.