AS3 creating dynamic Loader Names in a loop - actionscript-3

EDITED for clarity: I want to load all kinds of images from an external url in a for loop.
I want to call them in a loop and when it's over I start the loop again. however I don't want to call them again with an "http request" rather I would like to loop through the loaded images over and over again.
Is it possible to create a dynamic Loader name in a loop?
Here is the code example:
var Count = 0;
// Loop Begins
var Count:Loader = new Loader();
Count.load(new URLRequest("myurl");
addChild(Count);
Count++;
// End Loop
Another example would be to have a NAME and just add the number on the end. But how
var Count = 0;
// Loop Begins
var MyName+Count:Loader = new Loader();
MyName+Count.load(new URLRequest("myurl");
addChild(MyName+Count);
Count++;
// End Loop
IN SHORT:
I want to load a bunch of images into an Array and loop through the loaded images by calling them later.
Thanks so much!

CASE1 code is how to load images in Sequence.
CASE2 code is how to load images in Synchronized.
First, the URL you want to import all images must be named sequentially.
for example Must be in the following format:
www.myURL.com/img0.jpg
www.myURL.com/img1.jpg
www.myURL.com/img2.jpg
www.myURL.com/img3.jpg
www.myURL.com/img4.jpg
www.myURL.com/img5.jpg
.
.
.
Try the code below, just a test.
CASE1
var imgLoader:Loader;
var imgRequest:URLRequest;
var count:int = -1;
const TOTAL_COUNT:int = 10;
var imgBox:Array = [];
var isCounting:Boolean;
function loadImage():void
{
count ++;
isCounting = true;
imgLoader = new Loader();
imgRequest = new URLRequest();
imgRequest.url = "www.myURL.com/img" + count +".jpg";
imgLoader.load(imgRequest);
imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
if(count == TOTAL_COUNT)
{
isCounting = false;
count = -1;
}
}
function onLoadedImg(e:Event):void
{
imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadedImg);
var bmp:Bitmap = e.currentTarget.content;
bmp.x = Math.random() * width;
bmp.y = Math.random() * height;
bmp.width = 100;
bmp.height = 100;
this.addChild(bmp);
imgBox.push(bmp);
if( isCounting == false)
{
return;
}
loadImage();
}
function unloadedImg(e:IOErrorEvent):void
{
imgLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
trace("load Failed:" + e);
}
loadImage();
CASE2
var imgLoader:Loader;
var imgRequest:URLRequest;
const TOTAL_COUNT:int = 10;
var imgBox:Array = [];
function loadImage2():void
{
for(var i:int = 0; i<TOTAL_COUNT; i++)
{
imgLoader = new Loader();
imgRequest = new URLRequest();
imgRequest.url = "www.myURL.com/img" + i +".jpg";
imgLoader.load(imgRequest);
imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
}
}
function onLoadedImg(e:Event):void
{
imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadedImg);
var bmp:Bitmap = e.currentTarget.content;
bmp.x = Math.random() * width;
bmp.y = Math.random() * height;
bmp.width = 100;
bmp.height = 100;
this.addChild(bmp);
imgBox.push(bmp);
}
function unloadedImg(e:IOErrorEvent):void
{
imgLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
trace("load Failed:" + e);
}
loadImage2();
If you want access loaded Image. refer a following code. If you do not put them in an array can not be accessed in the future.
for(var int:i=0; i<TOTAL_COUNT; i++)
{
var bitmap:Bitmap = imgBox[i] as Bitmap;
trace("index: " + i + "x: " + bitmap.x + "y: " + bitmap.y, "width: " + bitmap.width + "height: " + bitmap.height);
}

Now that we're on the same page:
var imgArray:Array = new Array;
var totalImages:int = 42;
var totalLoaded:int = 0;
var loaded:Boolean = false;
function loadImages():void{
for(var count:int = 0; count < totalImages; count++){
var image:Loader = new Loader();
image.load(new URLRequest("image" + i + ".jpg");
image.addEventListener(Event.COMPLETE, loaded);
imgArray.push(image);
}
}
function loaded(e:Event):void{
totalLoaded++;
if (totalLoaded == totalImages){
loaded = true;
}
}
function displayImages():void{
if (loaded){
for(var i:int = 0; i < imgArray.length(); i++){
addChild(imgArray[i]);
}
}
}

Related

Timer related error in flash, TypeError #1009

I used a timer in my flash application, and I have this particular error below:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at FlashGame_fla::MainTimeline/toTimeCode()
at FlashGame_fla::MainTimeline/timerTickHandler()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Below is my code for this particular flash game application. It's a game where the player collects as many items as possible within a specific time:
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.geom.Rectangle;
menuButton.addEventListener(MouseEvent.CLICK, evilToMenu);
rulesButton.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.visible = false;
gameRules.buttonMode = true;
evilGameOverMC.visible = false;
evilWinLose.visible = false;
playAgainBtn.visible = false;
toMenuBtn.visible = false;
var pLives:int = 3;
var pEvilScore:int = 0;
var pItems:int = 10;
var daveMC:MovieClip;
var cGameObjs:Array = new Array();
var timer:Timer = new Timer(100, 300);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 15000;
//var cPlayerData:Object;
//var cSavedGameData:SharedObject;
addCharacter();
addBots();
addItems();
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
function evilToMenu(Event:MouseEvent):void
{
removeLeftovers();
removeChild(daveMC);
timer.stop();
gotoAndStop("menu");
}
function timerTickHandler(Event:TimerEvent):void
{
timerCount -= 100;
toTimeCode(timerCount);
if (timerCount <= 0)
{
gameOver(false);
}
}
function toTimeCode(milliseconds:int): void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timerDisplay.text = minutes + ":" + seconds;
}
function addCharacter():void
{
trace("Adding the character, Dave")
//set the initial values
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myXY:Array = [355,430];
var myChar:int = Math.ceil(Math.random() * 3);
var myKeys:Array = [37,39,38,40];
var myDistance:int = 7;
// create and add a new player object to the stage
daveMC = new Character(myBorder,myXY,myKeys,myChar,myDistance);
addChild(daveMC);
}
function addBots():void
{
trace("Adding the bots..");
// set the initial values (adapt to suit your game)
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myMaxBots:int = 5;// simulation
// add bots one at a time via a loop
for (var i:int = 0; i < myMaxBots; i++)
{
// create a new bot object and name it
var thisBot:Bot = new Bot(myBorder, daveMC);
thisBot.name = "bot" + i;
cGameObjs.push(thisBot);
// add it to the stage
addChild(thisBot);
}
}
function addItems():void
{
trace("Adding the items..");
//set the initial values
for (var i:int = 0; i < 10; i++)
{
// create a new bot object and name it
var thisItem:Item = new Item(daveMC);
thisItem.name = "item" + i;
cGameObjs.push(thisItem);
// add it to the stage
addChild(thisItem);
}
}
function updateLives(myBot:MovieClip):void
{
// update the player's LIVES and score
pLives--;
pEvilScore -= 30;
var myIndex:int = cGameObjs.indexOf(myBot);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pLives > 0)
{
updateScores();
}
else
{
gameOver(false);
}
}
function updateItems(myItem:MovieClip):void
{
// update the player's LIVES and score
pItems--;
pEvilScore += 20;
var myIndex:int = cGameObjs.indexOf(myItem);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pItems > 0)
{
updateScores();
}
else
{
gameOver(true);
}
}
function gameOver(myFlag:Boolean):void
{
updateScores();
if (myFlag)
{
// player wins
msgDisplay.text = "YAY! PAPPLE FOR \nEVERYBODY!";
removeLeftovers();
evilWinLose.text = "Weee!! We've got papples for Gru! \nYour Score: " + pEvilScore;
}
else
{
// player loses
msgDisplay.text = "OH NO! NOT \nENOUGH PAPPLES";
removeLeftovers();
evilWinLose.text = "Boo!! Not enough papples for Gru! \nYour Score: " + pEvilScore;
}
timerDisplay.text = "";
removeChild(daveMC);
evilGameOverMC.visible = true;
evilWinLose.visible = true;
toMenuBtn.visible = true;
playAgainBtn.visible = true;
toMenuBtn.addEventListener(MouseEvent.CLICK, Click_backtoMain);
playAgainBtn.addEventListener(MouseEvent.CLICK, backToEvil);
}
function updateScores():void
{
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
msgDisplay.text = pItems + " papples more to \ncollect..";
}
function removeLeftovers():void
{
// check each BOT/ITEM in array
for each (var myObj in cGameObjs)
{
myObj.hasHitMe();
myObj = null;
}
}
function backToEvil(event:MouseEvent):void
{
pEvilScore = 0;
pLives = 3;
pItems = 3;
gotoAndStop("menu");
gotoAndStop("evil");
}
Anyone can help me out with this? Thank you alot! :)
Replace your toTimeCode function code by :
function toTimeCode(milliseconds:int): void
{
trace(1);
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace(2);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
trace(3);
var seconds:String = String(time.seconds);
trace(4);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
trace(5);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
trace(6);
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
trace(7);
//display elapsed time on in a textfield on stage
timerDisplay.text = minutes + ":" + seconds;
trace(8);
}
Please, change the timerDisplay line to this one... The problem will be in the toTimeCode method. The error say that you are trying to call a method from a var wich is not (yet) an object...
if(null != timerDisplay)
timerDisplay.text = minutes + ":" + seconds;
You have to find an object wich is null! Add this :
function toTimeCode(milliseconds:int): void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace("Time: " + time);

Adding multiple movieclip from array

I got this function from internet which slice an image into part like tiles and put them in a array (linear or multidimensional).
---EXAMPLE---
var sliceClips:Array = sliceMovieClip({source:sourceMovieClip, target:tilesContainer, cols:7, rows:5}).linear;
So this is the function:
private function sliceMovieClip(o:Object):Object
{
var returnArray:Array = new Array();
var arrayLinear:Array = new Array();
var array2D:Array = new Array();
var cols:uint = o.cols;
var rows:uint = o.rows;
var tileWidth:uint = o.source.width / cols;
var tileHeight:uint = o.source.height / rows;
var rect:Rectangle = new Rectangle(0,0,tileWidth,tileHeight);
var pnt:Point = new Point();
var imageBMPD:BitmapData = new BitmapData(o.source.width,o.source.height,true,0x000000);
var imageBMP:Bitmap = new Bitmap(imageBMPD);
imageBMPD.draw(o.source);
for (var tY:uint = 0; tY < rows; tY++)
{
var arrayRow:Array = new Array();
for (var tX:uint = 0; tX < cols; tX++)
{
var sourceRect:Rectangle = new Rectangle(tX * tileWidth,tY * tileHeight,tileWidth,tileHeight);
var destPoint:Point = new Point(0,0);
var tileBMPD:BitmapData = new BitmapData(tileWidth,tileHeight,true,0x000000);
var tileBMP:Bitmap = new Bitmap(tileBMPD);
var tileMCL:MovieClip = new MovieClip();
tileMCL.addChild(tileBMP);
tileBMPD.copyPixels(imageBMPD, sourceRect, destPoint);
tileMCL.x = tX * tileWidth;
tileMCL.y = tY * tileHeight;
o.target.addChild(tileMCL);
returnArray.push(tileMCL);
arrayRow.push(tileMCL);
}
array2D.push(arrayRow);
}
return {linear:arrayLinear, multi:array2D};
}
I'm trying to add to stage those part of image sliced into different spot with a function like this (look at the last if):
private function buildMap(e:Event):void
{
for (var i:int=0; i<visAreaY; i++)
{
for (var u:int=0; u<visAreaX; u++)
{
if ((MapID[i][u]) == 0)
{
var cell:MovieClip = new tile();
cell.gotoAndStop(MapID[i][u]+1);
cell.x = tileSide * u;
cell.y = tileSide * i;
addChild(cell);
}
if ((MapID[i][u]) == 1)
{
var cell2:MovieClip = new blacksquare();
cell2.gotoAndStop(MapID[i][u]+1);
cell2.x = tileSide * u;
cell2.y = tileSide * i;
addChild(cell2);
}
if ((MapID[i][u]) == 2)
{
var cell3:MovieClip = sliceClips[2][0];
cell3.gotoAndStop(MapID[i][u]+1);
cell3.x = tileSide * u;
cell3.y = tileSide * i;
trace("Obj: " + cell3 + " w:" + cell3.width + " h:" + cell3.height + " pos:" + cell3.x + " " + cell3.y);
addChild(cell3);
}
}
}
}
There is a problem with cell3 (which use the sliced image) cause it seem to use the same image and doesnt duplicate it on my stage, so if i have it 4 time on my map it will only show the image on the last tile.
I was trying to do:
var cell3:MovieClip = new sliceClips[2][0];
but it won't accept my "new" cause its not a class.
Any idea how i can work this out? How can i set my movieclip array to a class or something.. I'm a beginner in as3
Given your sliced images use a single Bitmap object, the best you can do with this is clone a bitmap into a new MC.
if ((MapID[i][u]) == 2)
{
var cell3:MovieClip = new MovieClip();
cell3.addChild(new Bitmap((sliceClips[2][0].getChildAt(0) as Bitmap).bitmapData));
// main magic happens here ^ we get the bitmapdata of source MC
// then make a new bitmap AND a new MC with it
cell3.x = tileSide * u;
cell3.y = tileSide * i;
trace("Obj: " + cell3 + " w:" + cell3.width + " h:" + cell3.height + " pos:" + cell3.x + " " + cell3.y);
addChild(cell3);
}

AS3 Loading Image URLrequest - getBounds returns no values

I need to get the width and height of a flag I am loading into another movie so I can place it in the right location. Why is my getBounds not picking up the dimensions of the flag?
function displayFlags(evt:Event = null)
{
if(!Lang) { return; }
for (var i:uint = 0; i < Lang.length; i++)
{
//Language = new MovieClip();
//Language.name = Lang[i];
LangButton = new button01();
LangButton.name = Lang[i];
LangButton.btext.text = Lang[i];
LangButton.y = LangButton.height * i;
addChild(LangButton);
var flag:Loader = new Loader();
flag.load(new URLRequest(LangPath[i]+"/flag.png"));
/// Loads Flag into Button
LangButton.addChild(flag);
var fh = flag.getBounds(flag);
trace("FLAG HEIGHT = " + fh.height); // ZERO ZERO ZERO ZERO
// I really need this info to place the flag in the right location.
flag.y = (LangButton.height/2) - (flag.height/2);
}
evt.target.visible = false;
}
UPDATE: MAY 19TH, 2013
I was able to figure out that I need to wait for the flag to be loaded. Now I can get the correct Bounds.. however, now I can not get the movieClip "flag" in the load complete to respond. I don' think it sees the value of flag.
Below is my UPDATED code:
function displayFlags(evt:Event = null)
{
if(!Lang) { return; }
for (var i:uint = 0; i < Lang.length; i++)
{
//Language = new MovieClip();
//Language.name = Lang[i];
LangButton = new button01();
LangButton.name = Lang[i];
LangButton.btext.text = Lang[i];
LangButton.y = LangButton.height * i;
addChild(LangButton);
flag = new Loader();
flag.load(new URLRequest(LangPath[i]+"/flag.png"));
flag.name = Lang[i];
flag.contentLoaderInfo.addEventListener(Event.COMPLETE, loadedFlag(flag));
function loadedFlag()
{
return function()
{
var fh = flag.getBounds(flag);
trace("FLAG HEIGHT = " + fh);
trace("flag Name: "+ flag.name);
flag.alpha = .3;
}
}
LangButton.addChild(flag);
}
evt.target.visible = false;
}
try this :
flag.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
then add function :
function completeHandler(e:Event):void
{
var myFlagInfo:LoaderInfo = e.currentTarget as LoaderInfo;
var myFlag:Loader = myFlagInfo.loader;
var fh = myFlag.getBounds(myFlag);
}

Flash CS5 AS3 Can not get Flashvars

I am new to fairly new to AS3 and I have found myself needing to extend a fla. that was written by a 3rd party.
The goal is to access flashvars but for the life of me can not get it to work...been at it for days learning..
the fla I am working with is code on timeline with 2 frames. the movieclip runs to frame 2 ans stops.
On frame 2 is where I require the use of the flashvar.
I have built a simple example that will populate a textbox on frame two that works fine.
frame 1
var my_var:String = new String();
my_var = root.loaderInfo.parameters.uploadId;
frame 2
my_txt.text = my_var;
stop();
However when I use the same approach on my 3rd party fla I get NULL output. I am not using any TLF text either (I think).
I don't understand why it works in one case but not the other. I am thinking it might have to do with conflict with the surrounding code but I don't know enough about AS to track it down. Any help on this would be greatly appreciated.
frame 1
import net.bizmodules.uvg.loading;
stop();
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.showDefaultContextMenu = false;
stage.quality = StageQuality.BEST;
function RandomValue()
{
var d = new Date();
return String(d.getDate()) + String(d.getHours()) + String(d.getMinutes()) + String(d.getSeconds());
}
var my_var:String;
my_var = root.loaderInfo.parameters.uploadId;
var userId;
var albums:Object;
var resource:Object;
var strUploadPage:String;
if (root.loaderInfo.parameters.uploadPage != undefined)
strUploadPage = root.loaderInfo.parameters.uploadPage;
else
strUploadPage = "http://localhost/dnn450/desktopmodules/ultramediagallery/flashuploadpage.aspx?PortalId=0&ModuleId=455";
if (strUploadPage.indexOf("?") > 0)
strUploadPage += "&";
else
strUploadPage += "?";
strUploadPage += "action=loadAlbums&seed=" + RandomValue();
trace(strUploadPage);
var myLoading:MovieClip = new loading();
myLoading.x = (stage.stageWidth - myLoading.width) / 2;
myLoading.y = (stage.stageHeight - myLoading.height) / 2;
addChild(myLoading);
var myRequest:URLRequest = new URLRequest(strUploadPage);
var myLoader:URLLoader = new URLLoader(myRequest);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(evtObj:Event)
{
myLoader.removeEventListener(Event.COMPLETE, xmlLoaded);
try
{
var xDoc:XMLDocument = new XMLDocument();
xDoc.ignoreWhite = true;
var xml:XML = XML(myLoader.data);
xDoc.parseXML(xml.toXMLString());
userId=xDoc.firstChild.attributes.userId;
if (userId < 0)
{
removeChild(myLoading);
txtError.text = "Please ensure you are logged in";
return;
}
if(xDoc.firstChild.childNodes.length > 0)
{
albums = xDoc.firstChild.childNodes[0].childNodes;
resource = xDoc.firstChild.childNodes[1].attributes;
}
else
{
removeChild(myLoading);
txtError.text = xDoc.firstChild.attributes.error;
return;
}
play();
}
catch(e:Error)
{
removeChild(myLoading);
txtError.text = e + "\n\nPlease check your Event Viewer to find out detailed error message and contact service#bizmodules.net";
}
}
frame 2
import net.bizmodules.upg.Alert;
stop();
removeChild(myLoading);
initialize();
function initialize()
{
Alert.init(stage);
upload.addVar("userId",userId);
lstAlbums.dropdown.rowHeight = 24;
loadAlbums(0, albums);
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
var lastAlbum = my_so.data.lastAlbum * 1;
var foundLastAlbum = false;
if (lastAlbum > 0)
{
for (var i:int = 0; i< lstAlbums.length; i++)
{
if (lstAlbums.getItemAt(i).data == lastAlbum)
{
trace("find previous album");
foundLastAlbum = true;
lstAlbums.selectedIndex = i;
break;
}
}
}
if (!foundLastAlbum)
{
lstAlbums.selectedIndex = lstAlbums.length - 1;
}
albums_change(null);
lstAlbums.addEventListener("change", albums_change);
lstAlbums.setStyle("backgroundColor", 0x504C4B);
lstAlbums.dropdown.setStyle("backgroundColor", 0x504C4B);
lstAlbums.setStyle("themeColor", 0x1F90AE);
lstAlbums.setStyle("color", 0xC4C0BF);
lstAlbums.setStyle("textSelectedColor", 0xC4C0BF);
lstAlbums.setStyle("textRollOverColor", 0xC4C0BF);
lstAlbums.setStyle("alternatingRowColors", [0x504C4B, 0x504C4B]);
lstAlbums.setStyle("borderStyle", 'none');
}
my_txt.text = "hello" + " " + my_var;
function loadAlbums(level:int, xml:Object)
{
var prefix = " ".substring(0, level * 4);;
for (var i:int = 0;i<xml.length;i++)
{
var itemValue = xml[i].attributes.itemid;
if (xml[i].childNodes.length > 0)
itemValue *= -1;
lstAlbums.addItem({data: itemValue, label: prefix + xml[i].attributes.name});
if (xml[i].childNodes.length > 0)
{
loadAlbums(level + 1, xml[i].childNodes);
}
}
}
function albums_change(e)
{
var albumId = lstAlbums.getItemAt(lstAlbums.selectedIndex).data;
upload.set_albumId(albumId);
if (albumId > 0)
{
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
my_so.data.lastAlbum = albumId;
}
else
{
Alert.show("The album you choosed is invalid", null, 0xEAEAEA, 0x000000);
}
}
private var flashVarObj:Object = new Object;
flashVarObj=LoaderInfo(this.loaderInfo).parameters;
var my_var:String = new String();
my_var = flashVarObj.uploadIdd;

actionscript: access now object instance

my problem is that after I create the new movie clips I don't know how to access them
var numOfBalls:int = 5;
var balls:Array = new Array();
import flash.utils.getDefinitionByName;
function addBall(instanceName:String) {
var mcIName:String = "ball";
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
newMc.name = instanceName;
trace("added " + newMc.name);
newMc.x = randRange(10, 300);
newMc.y = randRange(10, 300);
addChild(newMc);
return this.newMc;
}
function randRange(start:Number, end:Number) : Number {
return Math.floor(start +(Math.random() * (end - start)));
}
var i = 0;
while ( i < numOfBalls) {
balls[i] = addBall("ball_" + i);
i++;
}
trace (this.balls[0]); // returnes error
trace (this.balls_0); //returnes error
function addBall(instanceName:String):MovieClip {
var mcIName:String = "ball";
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
newMc.name = instanceName;
trace("added " + newMc.name);
newMc.x = randRange(10, 300);
newMc.y = randRange(10, 300);
addChild(newMc);
return newMc;
}
That should fixe it. return typed to MovieClip, and the fix bit,
return newMc instead of this.newMc;
newMC doesn't belong to this.
if you had this.newMc = newMC maybe.
you need to specify what the addBall function is returning
function addBall(instanceName:String):MovieClip {
and you may have to push the balls into the balls array, like
balls[i].push(addBall("ball_" + i));
try this, i'm not sure about your problem
The only thing i can see is the index i where you write the name of the new MovieClip, in ActionScript3 you can't pass a numeric value to a String without convert it with toString() method, try to fix it and see if it works
var numOfBalls:int = 5;
var balls:Array = new Array();
import flash.utils.getDefinitionByName;
function addBall(instanceName:String):MovieClip {
var mcIName:String = "ball";
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
newMc.name = instanceName;
trace("added " + newMc.name);
newMc.x = randRange(10, 300);
newMc.y = randRange(10, 300);
addChild(newMc);
return this.newMc;
}
function randRange(start:Number, end:Number) : Number {
return Math.floor(start +(Math.random() * (end - start)));
}
var i = 0;
while ( i < numOfBalls) {
// convert i with toString() is requested in as3 or will return ERRORS
balls.push(addBall("ball_" + i.toString ()));
i++;
}
trace (MovieClip(this.balls[0]));