AS3: Adding function to population loop - function

Basically I have 2 movieclip objects with some code, currently just to trace them. The blue circles when clicked will say 'Blue' and the red ones when clicked will say 'Red'. This works fine in theory until I add a population loop, which adds more of them. Then only 1 of each colour correctly works, the rest are just 'mock' circles. I wish for each circle to tell me their colour.
This is my code for the .fla:
import flash.events.MouseEvent;
BlueBall.addEventListener(MouseEvent.CLICK, fun1)
function fun1(e:MouseEvent){
trace("Blue!");
}
RedBall.addEventListener(MouseEvent.CLICK, fun2)
function fun2(e:MouseEvent){
trace("Red!");
}
and this is the population loop in an .as file:
private function PopulateCircles():void
{
for (var i:int=0; i < 10; i++)
{
var blueCircle:BlueCircle = new BlueCircle();
this.addChild(blueCircle);
var redCircle:RedCircle = new RedCircle();
this.addChild(redCircle);
}
}
tldr; how do I get the on-click events to occur on every newly populated circle?

Pretty easy, actually. Just as you subscribe method to listen the predesigned instances' events, you can subscribe via temporary variable references. As long, as the variable holds the reference (or a pointer in C++ terms), you can address the instance and do anything you could do to a predesigned MovieClip:
private function PopulateCircles():void
{
var aRed:RedCircle;
var aBlu:BlueCircle;
for (var i:int = 0; i < 10; i++)
{
// If there are no mandatory constructor arguments,
// you can omit the () brackets.
aRed = new RedCircle;
aBlu = new BlueCircle;
// Disperse clips to random places.
aBlu.x = 500 * Math.random();
aBlu.y = 500 * Math.random();
aRed.x = 500 * Math.random();
aRed.y = 500 * Math.random();
// Subscribe methods to newly created instances.
aRed.addEventListener(MouseEvent.CLICK, fun2);
aBlu.addEventListener(MouseEvent.CLICK, fun1);
// You're operating inside 'this' object,
// no need to explicitly point it out.
addChild(aRed);
addChild(aBlu);
}
}

Related

AS3 shuffling movieclips

I've added the basic targets and applying drag and drop for my puzzle pieces, now Im having trouble making the shuffling aspect. As in, after the player completes or opens up the fla, each time will start the puzzle pieces in random places of the stage. I understand using arrays for shuffling somehow but Im not sure exactly how to achieve this. I've stored the instance of my 19 puzzle pieces inside the array but now I have no idea what to do with this array. Other tutorials were abit out of my league and leaves my head scratching.
Just started doing coding for flash professional so yeah, any help with the shuffling movie clips ie the puzzles pieces would be greatly appreciated.
Heres's my code, Im not posting the whole thing since from P1 to P19 is basically copy pasting:
import flash.events.Event;
stage.addEventListener(Event.ENTER_FRAME, EntFrame)
function EntFrame(e: Event) : void
{
P1.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void
{
P1.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void
{
P1.stopDrag();
}
if (T1.hitTestObject(P1.Tar1))
{
P1.x = 313.15;
P1.y = 242.75;
}
P19.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_19);
function fl_ClickToDrag_19(event:MouseEvent):void
{
P19.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_19);
function fl_ReleaseToDrop_19(event:MouseEvent):void
{
P19.stopDrag();
}
if (T19.hitTestObject(P19.Tar19))
{
P19.x = 624.35;
P19.y = 455.60;
}
}
Here is what I hope is more holistic answer.
First, ditch those inline functions. Right now you make an ENTER_FRAME listener and inside that function you have inline function defined. This means every frame tick (which is tied to your frame rate, not the main timeline), those functions are going to get created again, and since you are adding them as handlers for listeners, they will stay in memory forever.
Here is a way you code this, showing ways to reduce redundancy and get rid of those memory leaks. This assumes the following:
You have 19 objects on the stage called T1 - T19, that represent the possible locations the pieces can go.
You have 19 pieces on the stage called P1 - P19, that, and the numbers correlate to the T locations as per the correct location of the piece.
//let's create a function to randomize the piece location
function seedPieces() {
//create an array consisting of the integers 1 - 19
var unusedSpaces:Vector.<int> = new Vector.<int>;
var i:int;
for (i = 1; i <= 19; i++) {
//populate that array
unusedSpaces.push(i);
}
var curLocation:DisplayObject; //helper var for the loop below
var curPiece:Sprite; //helper var for the loop below
//loop 19 times (from 1 - 19) - one iteration for each piece
for (i = 1; i <= 19; i++) {
curPiece = this["P" + i] as Sprite; //you can get the piece this way, or use an array if you've made one, like `pieces[i];`
trace(curPiece.name);
//splice removes and returns the item at the specified index (in this case a random number between 0 and arrays length less 1) - the second parameter is amount of items to remove (just 1 for this case)
curLocation = this["T" + unusedSpaces.splice(int(Math.random() * unusedSpaces.length), 1)] as DisplayObject;
trace(" ",curLocation.name);
//move the piece to the random location:
curPiece.x = curLocation.x;
curPiece.y = curLocation.y;
}
}
//NOW, as an aside, you should use a loop to add all your listeners for the sake of sanity - if you have them in an array, loop through that, or use the sloppy way like this:
for (var i:int = 1; i <= 19; i++) {
Sprite(this["P" + i]).addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
}
//create a var to hold any piece that is currently being dragged, so you know which piece to stop drag on later
var currentDraggingItem:Sprite;
seedPieces();
function fl_ClickToDrag(event:MouseEvent):void
{
//assign this clicked item to the currentDraggingItem var
currentDraggingItem = event.currentTarget as Sprite;
//bring this one to the front
currentDraggingItem.parent.addChild(currentDraggingItem);
//you can use this one click handler for all pieces
//the piece that was actually clicked, is referenced by event.currentTarget
currentDraggingItem.startDrag();
//add the mouse up listener now that the mouse is currently DOWN
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
//listen every frame while dragging
stage.addEventListener(Event.ENTER_FRAME, EntFrame);
}
function fl_ReleaseToDrop(event:MouseEvent):void
{
//if currentDraggingItem has a value, stop drag it
if (currentDraggingItem) {
currentDraggingItem.stopDrag();
//send to the back
currentDraggingItem.parent.addChildAt(currentDraggingItem,0);
}
//remove the mouse up and enter frame listener now that the mouse is UP
stage.removeEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
stage.removeEventListener(Event.ENTER_FRAME, EntFrame);
if(checkComplete()){
//game over, do something
}
}
function EntFrame(e: Event) : void
{
//this will snap the peice to the correct spot when the mouse is touching the correct spot
if(currentDraggingItem){
if (this[currentDraggingItem.name.replace("P","T")].hitTestPoint(mouseX,mouseY))
{
currentDraggingItem.x = this[currentDraggingItem.name.replace("P","T")].x;
currentDraggingItem.y = this[currentDraggingItem.name.replace("P","T")].y;
}
}
}
function checkComplete():Boolean {
//use a loop to go through all your pieces and check if they are in the right spot. Again, you could have them in an array, or do it the lazy way
for (var i:int = 1; i <= 19; i++) {
if (!this["T"+i].hitTestObject(this["P"+i]))
{
return false;
}
}
return true;
}
Well, in general you can shuffle with the following code:
var shuffledVector:Vector.<someClass> = new Vector.<someClass>;
while (originalVector.length > 0) {
shuffledVector.push(originalVector.splice(Math.random() * originalVector.length, 1)[0]);
}
Longer, explained version:
var shuffledVector:Vector.<someClass> = new Vector.<someClass>; //We will store our shuffled vector in here
var randomIndex:int; //Random index from the originalVector
var resultVector:Vector.<someClass>; //result from the originalVector.splice(...) function
var randomElement:someClass; //Random element from the originalVector
while (originalVector.length > 0) { //We will reduce the size of the originalVector until the originalVector is empty.
randomIndex = Math.random() * originalVector.length; //Calculate a random index within the range of the originalVector from 0 to originalVector.lenght-1 (note that the range decreases by one on every loop)
randomVector = originalVector.splice(randomIndex, 1); //Use splice to remove one element at the randomly choosen index, we will receive a vector with the removed element...
randomElement = randomVector[0]; //...so we need to access the element
shuffledVector.push(randomElement); //Add the randomly choosen element to our shuffled vector
}
I've written the code for a vector as i suggest to use a vector instead of an array, but the principle behind it is the same for an array.
In your case the originalVector is a vector filled with your P1-P19 Movieclips and someClass would be MovieClip. The originalVector is empty at the end and could be replaced with the shuffled one and of course it would make a lot more sense if you put the code in a seperate function like this:
function Shuffle(originalVector:Vector.<someClass>) : void {
var shuffledVector:Vector.<someClass> = new Vector.<someClass>;
while (originalVector.length > 0) {
shuffledVector.push(originalVector.splice(Math.random() * originalVector.length, 1)[0]);
}
originalVector = shuffledVector;
}
Offtopic, but important for further coding: Someone else already mentioned, that it is not good to add EventListeners on every frame, because it is absolutely unnecessary. You only need to add the Listeners once. Your code is very repetitive, you should use a function which accepts a MovieClip, x and y then call that function 19 times.
e.g.:
function setUpMovieClip(MC:MovieClip, x:int, y:int) : {
MC.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag);
//more code...
}
within the clickToDrag function you can access the MovieClip which was clicked via the event.target property:
function clickToDrag(e:MouseEvent) : {
e.target.startDrag();
//more code...
}
I hope you get the idea.

AS3 - Using a For Loop to Update Multiple Points and Their Values in an Array

I'm a bit new with AS3 (but not really with coding) so please forgive my ignorance. I'm creating a small function that will be called by a Main Function to update the position of 52 Pointers that have the x and y position of multiple point objects (empty movie clips). It will also then update two global arrays with those values (one array for the x and one for the y).
The problem is, as there are 52 of them, and they will probably grow in quantity, I'd like to be able to use a FOR function to do it, but I can't seem to be able to figure it out.
I get this error: Access of undefined property _point.
Here is a piece of the code that dream about:
function happyFunc():void
{
var avpointers:int = 52;
var vpointx:Array = new Array();
var vpointy:Array = new Array();
for (aa=0; aa<vpointers; aa++)
{
vpointx[aa] = _point[aa].x;
vpointy[aa] = _point[aa].y;
}
}
And this is the code that I'm stuck with...
function reallySadFunc():void
{
_point1 = localToGlobal(new Point(point1.x,point1.y));
//...
_point52 = localToGlobal(new Point(point52.x,point1.y));
vpointx[0] = _point1.x;
vpointx[1] = _point2.x;
//...
//oh god there are 104 lines of this why do I have to suffer
}
Thank you!
If I read your question correctly, I think this is what you need:
public static const CLIP_COUNT:int = 52;
// ...
private function happyFunc(parentClip:DisplayObjectContainer):void
{
var vpointx:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var vpointy:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var clipPoint:Point = new Point ();
var globalPoint:Point;
for (var i:int = 0; i < CLIP_COUNT; i++)
{
var childClip:DisplayObject = parentClip.getChildByName("point" +
(i + 1).toString());
clipPoint.x = childClip.x;
clipPoint.y = childClip.y;
globalPoint = parentClip.localToGlobal(clipPoint);
vpointx[i] = globalPoint.x;
vpointy[i] = globalPoint.y;
}
// do something with vpointx and vpointy - they're local variables
// and will go out of scope unless you declare them as class members
// or somehow return them from this function.
}
This function works by taking the parent display object (the one that contains the 52 movie clips - this could be the Stage) and iterates through them by getting each movie clip by name. The code assumes that your movie clips are called point1, point2, ..., point52.
To speed up the local-to-global coordinate conversion, two Point objects are created and then reused during the for loop to avoid creating many temporary Point instances.
Instead of using Array, use Vector.<Number> - this class has better performance than Array does.

how to create element only after previous is on stage

How do i add a new element only after the previous one has passed the stage.stageWidth / 2
except by my way (the code below ,where i create a zone that the element will pass only one time)
PS:I dont want to do it like this cause the speed of movement will be different in time (it will slowly go up and down). Like from 3 to 6 by a easing factor of 0.005
so far i have this
import flash.display.MovieClip;
import flash.events.Event;
public class Main extends MovieClip
{
private var myArray:Array = new Array();
public function Main()
{
stage.addEventListener(Event.ENTER_FRAME, everyFrame)
var item:Box = new Box();
item.x = stage.stageWidth - 100
item.y = 40
addChild(item)
myArray.push(item)
}
private function everyFrame(ev:Event):void
{
var myBox:Box
for(var i:int = 0; i< myArray.length; i++)
{
myBox = myArray[i]
myBox.x -=3
if(myBox.x <= stage.stageWidth/2 && myBox.x >= stage.stageWidth/2 - 3)
{
trace("new Box")
var myNewBox:Box = new Box()
myNewBox.x = stage.stageWidth - 100
myNewBox.y = 40
addChild(myNewBox)
myArray.push(myNewBox)
}
if(myBox.x < 0 )
{
removeChild(myBox)
myArray.splice(i, 1)
trace(myArray.length)
}
}
}
}
Your code is already working and do things as you required.
The code looks like document class, but there is one little mistake that prevent it from execution. You forget package{...} wrap.
But you compiler should say you about this, didn't it?
You are right, using range can provide you bunch of problems then objects didn't get in it, or get several times.
To solve this you could not check area but only myBox.x<= stage.stageWidth/2 condition. After object met this condition, just remove element from array you use for checking and add it to array of objects which you check for leaving stage to delete them.
If you don't want make another array, you could add some property to every new Box.
For example - passedCenter and set it to false. Then change if statement for
if(myBox.x <= stage.stageWidth/2 && !myBox.passedCenter){
myBox.passedCenter=true;
//you stuff
}

AS3 - Dynamically re-populate a series of textFields held within a group of MovieClips

I’ve come across a problematic issue with some functionality I’m attempting to develop in ActionScript3 on the Flash Professional CS5 platform and was wondering if anybody could point me in the right direction with it?
Background
Within my ActionScript Class, I have written a MouseEvent function which dynamically adds multiple instances of the same MovieClip (user_shape) on to the stage in the formation of a shape that the user has designed in an earlier stage of the program.
This shape effect is achieved through a For Loop that loops through the entire length of a Multi-Dimensional Boolean based array looking for an instance of true (determined by the user’s actions earlier) and then adding a MovieClip to the stage if this is the case.
Each group of MovieClips added with a single click, while always having the same instance name (user_shape), is always assigned a unique ID, which I've set up by including a numerical variable that increments up by 1 each time I add the batch of 'user_shape' MovieClips through left click to the stage.
The user can pick from up to eight different colours to assign to their shape (via selection boxes) before adding it to the stage. For each of these eight colours I have added a numerical variable (shapeCounterBlue, shapeCounterRed etc.) which basically counts ++ every time I add a shape of a certain colour to the stage and likewise it counts -- if I chose to remove a shape.
As a shape is added through my main function I attach a dynamic textField to each MovieClip and populate it with the variable counter number for the particular colour I have selected (see image below).
Problem
OK, so here is my issue. I need my unique number (displayed in white) for each coloured shape to dynamically re-populate and update when I remove a shape from the stage. As you can see in the image I’ve attached, if I were to remove the second blue shape, my third blue shape’s numbers would need to revert from 3 to 2.
Likewise if I had six red shapes on the stage and I decided to remove the third one, then shapes 4,5,6 (before 3 is deleted), would need to have their numbers changed to 3,4,5 respectively.
Or I could have four green shapes and remove the first shape; this would mean that shapes 2,3,4 would actually need to change to be 1,2,3.
You get the idea. But does anybody know how I could achieve this?
My problem has further been hampered by the fact that the textFields for each MovieClip are added dynamically through my For Loop to the user_shape Child. This means that within my AS class, I haven’t been able to publicly declare these textFields and access the values within them, as they only exist in the For Loop used in my add shape function and no where else.
Many thanks in advance.
as to the targeting dynamically created text fields. In your loop assign a name that you can later access.
for(i:int=0;i<myArray.length;i++){
var txt:TextField = new TextField();
txt.name = "txt_" + i;
this.addChild(txt);
}
Then to access your textfields outside the loop target them like this:
var targetTxt:TextField = this.getChildByName("txt_10");
UPDATE
Ok so I had some time and went ahead and solved your entire problem
(Download Source FLA/AS files)
Ok so there are some MCs in the library that I call in my code. I created a Box MC that has a label textfield, a border, and a background MC that I can target to color.
I created a countColors() that loops over all the boxes once you have click on one (triggered from a mouseEvent within each box). It counts the different colors totals in an array and then sends a custom event to let all the boxes know they can fetch the color totals to update their labels.
I hope this helps.
main.as
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
public class main extends MovieClip {
public static var ROOT:MovieClip;
public var totalBoxes:int = 100;
public var boxContainer:Sprite;
public static var colorArray:Array = [0xFF0000, 0x0000FF, 0x00FF00];
public static var colorCount:Array = [0,0,0];
public static var currentColor = 0;
public function main() {
// set ref to this
ROOT = this; // so I can get back to it from the boxes
// color selection
redBtn.addEventListener(MouseEvent.CLICK, chooseColor);
blueBtn.addEventListener(MouseEvent.CLICK, chooseColor);
greenBtn.addEventListener(MouseEvent.CLICK, chooseColor);
// add box container to stage
boxContainer = new Sprite();
boxContainer.x = boxContainer.y = 10;
this.addChild(boxContainer);
var row:int=0;
var col:int=0;
for(var i:int=0; i < totalBoxes; i++){
var box:Box = new Box();
box.x = col * box.width;
box.y = row * box.height;
box.name = "box_" + i;
box.ID = i;
box.updateDisplay();
boxContainer.addChild(box);
if(col < 9){
col++;
}else{
col = 0;
row++;
}
}
}
private function chooseColor(e:MouseEvent):void
{
var btn:MovieClip = e.currentTarget as MovieClip;
switch(btn.name)
{
case "redBtn":
currentColor=0;
break;
case "blueBtn":
currentColor=1;
break;
case "greenBtn":
currentColor=2;
break;
}
// move currentColorArrow
currentColorArrow.x = btn.x;
}
public function countColors():void
{
colorCount = [0,0,0]; // reset array
for(var i:int=0; i < totalBoxes; i++){
var box:Box = boxContainer.getChildByName("box_" + i) as Box;
if(box.colorID > -1)
{
colorCount[ box.colorID ]++;
}
}
// send custom event that boxes are listening for
this.dispatchEvent(new Event("ColorCountUpdated"));
}
}
}
Box.as
package {
import flash.display.MovieClip;
import flash.geom.ColorTransform;
import flash.events.MouseEvent;
import flash.events.Event;
public class Box extends MovieClip {
public var ID:int;
public var colorID:int = -1;
private var active:Boolean = false;
private var bgColor:Number = 0xEFEFEF;
public function Box() {
this.addEventListener(MouseEvent.CLICK, selectBox);
main.ROOT.addEventListener("ColorCountUpdated", updateCount); // listen to root for custom event to update display
}
public function updateDisplay() {
if(active == false){
boxLabel.htmlText = "<font color='#000000'>"+ ID +"</font>";
}else{
boxLabel.htmlText = "<font color='#FFFFFF'>"+ main.colorCount[colorID] +"</font>";
}
var myColorTransform = new ColorTransform();
myColorTransform.color = bgColor;
boxBG.transform.colorTransform = myColorTransform;
}
private function selectBox(e:MouseEvent):void
{
// set bgColor
if(active == false){
bgColor = main.colorArray[main.currentColor];
colorID = main.currentColor;
}else{
bgColor = 0xEFEFEF;
colorID = -1;
}
// set active state
active = !active // toggle true/false
main.ROOT.countColors();
}
private function updateCount(e:Event):void
{
updateDisplay();
}
}
}

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.