Flash CS5 AS3 Can not get Flashvars - actionscript-3

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;

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);

error while converting AS2 starfield code to AS3

I've tried to convert a nice AS2 script for starfirld effect to AS3 But i'm still getting strange errors
would really appreciate if any one could help me understand what am i doing wrong
here is the original AS2 code:
var stars = 100;
var maxSpeed = 16;
var minSpeed = 2;
var i = 0;
while (i < stars)
{
var mc = this.attachMovie("star", "star" + i, i);
mc._x = random(Stage.width);
mc._y = random(Stage.height);
mc.speed = random(maxSpeed - minSpeed) + minSpeed;
var size = random(2) + 6.000000E-001 * random(4);
mc._width = size;
mc._height = size;
++i;
} // end while
this.onEnterFrame = function ()
{
for (var _loc3 = 0; _loc3 < stars; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = Stage.height;
_loc2.speed = random(maxSpeed - minSpeed) + minSpeed;
_loc2._x = random(Stage.width);
} // end of for
};
and here is my AS3 version:
import flash.events.Event;
import flash.events.MouseEvent;
function starField():void
{
var stars:int = 100;
var maxSpeed:int = 16;
var minSpeed:int = 2;
var i:int = 0;
while (i < stars)
{
var mc = new Star();
addChild(mc)
mc._x = Math.random()(stage.stageWidth);
mc._y = Math.random()(stage.stageHeight);
mc.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
var size = Math.random()(2) + 6.000000E-001 * Math.random()(4);
mc._width = size;
mc._height = size;
++i;
} // end while
}
addEventListener(Event.ENTER_FRAME, update);
function update(_e:Event):void
{
for (var _loc3 = 0; _loc3 < 100; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = stage.stageHeight;
_loc2.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
_loc2._x = Math.random()(stage.stageWidth);
} // end of for
};
the error message I'm getting is: "TypeError: Error #1010: A term is undefined and has no properties. at _fla::MainTimeline/update()"
I understand it has a problem with the 'update' function but I'm net sure which term it refer to?
I'll bet a can of juice here is your problem:
var _loc2 = this["star" + _loc3];
put these into an associative array and access them from there.
#Discipol is right.
Just wanted to add a few more notes:
You can also use the display list to get the movie clip by name:
var _loc2:MovieClip = MovieClip(getChildByName("star" + _loc3));
You've got untyped variables and your are relying on MovieClip as a dynamic class to add properties (such as speed) at runtime. For a really simple project the impact is barely noticeable, but on the long run, for bigger projects, it's worth extending Sprite if you don't use the timeline and add the properties you need:
package {
import flash.display.Sprite;
import flash.events.Event;
public class Star extends Sprite {
private var speed:Number;
private var minSpeed:Number;
private var maxSpeed:Number;
public function Star(min:Number,max:Number) {
minSpeed = min;
maxSpeed = max;
var size = (Math.random()*2) + 1.82211880039 * (Math.random()*4);
width = size;
height = size;
this.addEventListener(Event.ADDED_TO_STAGE,reset);
}
private function reset(e:Event = null):void{
speed = (Math.random() * (maxSpeed-minSpeed)) + minSpeed;
x = Math.random() * stage.stageWidth;
if(e != null) y = Math.random() * stage.stageHeight;//initialized from added to stage event
else y = stage.stageHeight;//otherwise reset while updating
}
public function update():void{
if (y > 0) y -= speed;
else reset();
}
}
}
and the rest of the code would be as simple as:
var stars:int = 100;
var starClips:Vector.<Star> = new Vector.<Star>(stars,true);//a typed fixed vector is faster than a dynamically resizable untyped Array
for(var i:int = 0 ; i < stars; i++) starClips[i] = addChild(new Star(16,2)) as Star;
this.addEventListener(Event.ENTER_FRAME,updateStars);
function updateStars(e:Event):void{
for(var i:int = 0 ; i < stars; i++) starClips[i].update();
}

Flash only removing objects not created through code

I'm trying to make a simple game in Flash. So far, I've added a bunch of objects to the stage using addChild(objName);. However, now I'm trying to remove the objects completely. I don't want to have to cycle through every object's name and I'm sure there must be a more efficient way to select each object (maybe by index on the stage) and removeChildAt(index); it. However, when I try this, Flash only removes the objects that were manually placed by me on the stage. It doesn't remove the ones that were placed through code. I've done some searching and I tried multiple methods, all of which yield the same result. The one that most people agree on is this one:
while (numChildren > 0)
{
removeChildAt(0);
}
Can you help me figure out why this isn't removing anything that was coded onto the stage?
Thanks in advance :D
Edit: Here is my code for the frames:
Frame 1 (Randomly generates and displays the dots):
import flash.events.MouseEvent;
import fl.motion.easing.Linear;
var dotList = new Array(); var level:int = 3; var invisoDotList = new Array();
var loop:int;
var line:Line = new Line();
line.x = 274;
line.y = 187;
addChild(line);
for(loop = 0; loop < level; loop++)
{
var dot:Dot = new Dot();
var invisoDot:InvisoDot = new InvisoDot();
var tester:Boolean = true;
var xval:int = Math.floor(Math.random()*(1+520))+14;
var looper:int = 0;
while(looper < dotList.length)
{
if(Math.abs(xval - dotList[looper].x) > 30)//minimum spacing
{
looper++;
}
else
{
looper = 0;
xval = Math.floor(Math.random()*(1+520))+14;
}
}
dot.x = xval;
dot.y = 187;
invisoDot.x = xval;
invisoDot.y = 187;
invisoDot.alpha = 0;
dotList[loop] = dot;
invisoDotList[loop] = invisoDot;
addChild(invisoDot);
addChild(dot);
}
//trace(dotList); test to ensure that dots are added to the array
var nb1:NextButton = new NextButton();
nb1.x = 0;
nb1.y = 0;
nb1.alpha = 0;
addChild(nb1);
nb1.addEventListener(MouseEvent.CLICK, hideDots);
function hideDots(e:MouseEvent)
{
for(var loop:int = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
line.alpha = 0;
nextFrame();
}
stop();
Frame 2 (Displays further instructions and contains a couple of methods that will be used later on):
import flash.events.MouseEvent;
removeChild(nb1);
var nb2:NextButton = new NextButton();
nb2.x = 0;
nb2.y = 0;
nb2.alpha = 0;
addChild(nb2);
nb2.addEventListener(MouseEvent.CLICK, next);
function next(e:MouseEvent)
{
nextFrame();
}
function clearStage()
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
stop();
Frame 3 (Makes the dots disappear when they are clicked and keeps an accuracy count):
import flash.events.MouseEvent;
import flash.utils.Timer;
line.alpha = 1;
removeChild(nb2);
//setChildIndex(line,0);
var clicks:int = -1;
var passed:int = 0;
var fromLine:Boolean = false;
//trace(dotList.length);
stage.addEventListener(MouseEvent.CLICK, clickCount);
for(var loopvar:int = 0; loopvar < dotList.length; loopvar++)
{
//trace("loop");
dot = dotList[loopvar];
invisoDot = invisoDotList[loopvar];
dot.addEventListener(MouseEvent.CLICK, onClick);
invisoDot.addEventListener(MouseEvent.CLICK, onClick);
//trace("event");
}
//trace(dotList.length);
function onClick(e:MouseEvent)
{
//e.currentTarget.alpha = .5;
for(var hitcheck:int = 0; hitcheck < dotList.length; hitcheck++)
{
if(dotList[hitcheck].x == e.currentTarget.x)
{
dotList[hitcheck].alpha = 1;
}
}
//trace("check");
}
var numChanged:int = 0;
function clickCount(e:MouseEvent)
{
clicks++;
//trace(clicks);
numChanged = 0;
for(var index:int = 0; index < dotList.length; index++)//check whether the user has gotten all the dots
{
if(dotList[index].alpha == 1)
{
numChanged++;
}
}
if(numChanged == level)//if the user has gotten all the dots
{
/*trace("next screen for sucess");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
if((clicks - level) == 1)
{
passed = 2
}
else if((clicks - level) == 0)
{
passed = 1;
}
passed = 1;
fromLine = true;
nextFrame();
}
else if((clicks - numChanged) >= 2)//this ends the session as soon as 2 mistakes are made
{
/*trace("next screen for failed number of clicks");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
passed = 3;
fromLine = true;
nextFrame();
}
/*else if((clicks - level) >= 2)//if the user has made too many mistakes. This ends the session after the maximum number of tries have been used
{
trace("next screen too many clicks");
trace(clicks);
}*/
}
//trace("end");
stop();
Frame 4 (Generates the results table. A sidenote: there is a bug where "Okay" is never a result because in Frame 3, the value of passed never equals 2. Not sure why though):
import flash.text.TextFormat;
import flash.text.TextField;
var failFormat:TextFormat = new TextFormat();
failFormat.color = 0xFF0000;
failFormat.font = "Arial";
failFormat.size = 18;
var passFormat:TextFormat = new TextFormat();
passFormat.color = 0x00FF00;
passFormat.font = "Arial";
passFormat.size = 18;
var okayFormat:TextFormat = new TextFormat();
okayFormat.color = 0x808000;
okayFormat.font = "Arial";
okayFormat.size = 18;
var normalFormat:TextFormat = new TextFormat();
normalFormat.color = 0x000000;
normalFormat.font = "Arial";
normalFormat.size = 18;
var lineResults = new Array();
var squareResults = new Array();
trace(passed);
if(fromLine == true)
{
if(passed == 1)
{
lineResults[lineResults.length] = "Pass";
}
else if(passed == 2)
{
lineResults[lineResults.length] = "Okay";
}
else if(passed == 3)
{
lineResults[lineResults.length] = "Fail";
}
}
fromLine = false;
lineResults = lineResults.reverse();
squareResults = squareResults.reverse();
var loopLength:int = (lineResults.length >= squareResults.length) ? lineResults.length : squareResults.length;
var loopStart:int = 0;
if(loopLength > 11)
{
loopStart = loopLength - 12
}
var cb:CellBlock = new CellBlock();
cb.x = 283.05;
cb.y = 20.35;
addChild(cb);
var col1Head:TextField = new TextField();
col1Head.defaultTextFormat = normalFormat;
col1Head.text = "# of Dots";
col1Head.x = 114.95
col1Head.y = 8.3;
addChild(col1Head);
var col2Head:TextField = new TextField();
col2Head.defaultTextFormat = normalFormat;
col2Head.text = "Line";
col2Head.x = 259.95
col2Head.y = 8.3;
addChild(col2Head);
var col3Head:TextField = new TextField();
col3Head.defaultTextFormat = normalFormat;
col3Head.text = "Square";
col3Head.x = 381.95
col3Head.y = 8.3;
addChild(col3Head);
for(loop = loopStart; loop < loopLength; loop++)
{
var block:CellBlock = new CellBlock();
block.x = 283.05;
block.y = 20.35 + (loop - loopStart + 1)*33;
addChild(block);
var col2:TextField = new TextField();
var col3:TextField = new TextField();
var col1:TextField = new TextField();
/*col2.defaultTextFormat = passFormat;
col3.defaultTextFormat = okayFormat;*/
col1.defaultTextFormat = normalFormat;
switch(lineResults[loop])
{
case "Pass":
col2.defaultTextFormat = passFormat;
break;
case "Okay":
col2.defaultTextFormat = okayFormat;
break;
case "Fail":
col2.defaultTextFormat = failFormat;
break;
}
switch(squareResults[loop])
{
case "Pass":
col3.defaultTextFormat = passFormat;
break;
case "Okay":
col3.defaultTextFormat = okayFormat;
break;
case "Fail":
col3.defaultTextFormat = failFormat;
break;
}
//col2.text = "Pass";
col2.text = lineResults[loop];
col2.x = 260.95;
col2.y = block.y - 12;
addChild(col2);
//col3.text = "Okay";
try
{
col3.text = squareResults[loop];
}
catch(e:Error)
{
}
col3.x = 386.95;
col3.y = block.y - 12;
addChild(col3);
col1.text = String(loop + 1);
col1.x = 133.95;
col1.y = block.y - 12;
addChild(col1);
}
var nb4:NextButton = new NextButton();
nb4.x = 0;
nb4.y = 0;
nb4.alpha = 0;
addChild(nb4);
nb4.addEventListener(MouseEvent.CLICK, clearStage);
stop();
Frame 5 (Next frame which is a test to make sure that everything gets erased, which it doesn't):
removeChild(nb4);
stop();
This error:
ArgumentError: Error #1063: Argument count mismatch on Game_fla::MainTimeline/clearStage(). Expected 0, got 1. clearStage()
Occurs because your clearStage() method has been added as the click event handler of a button. If your clearStage() function is going to be used an an event handler, it needs to accept an "event" parameter. So you should define the function like this:
function clearStage(event:Event)
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
As a side note, this means that if you want to also call clearStage() manually, that is use it without adding it as an event handler, that you'll need to include this event parameter... but you can just pass in a null, because your code doesn't need to actually use the event parameter:
clearStage(null);
I'm not sure I see anything else wrong. I'd start by adding that event parameter to your clearStage() function as I shown above.
I should also add I mostly worked in Flex or pure AS3, and am not super skilled in Flash CS6 and programming on the timeline :)
From memory, I don't think Flash re-orders when you remove a child. If you remove a child at index 0, every other child is still numbered 1 to x. childAt(0) is just null now. Keep that in mind with this sort of process.

AS3 creating dynamic Loader Names in a loop

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]);
}
}
}

AS3 Showing image after load is finish

So i'm loading picture from xml, and adding them into a movieclip called cv which has a holder called cHolder. Right now the problem is that while the preloader shows it is loading, the cv(s) appeared already. Is there anyway to show all the cv only after the images have finish loading?
Thanks.
for each (var projectName:XML in projectAttributes)
{
//trace(projectName);
var projectDP:XMLList = projectInput.project.(#name == projectName).displayP;
//trace(projectDP);
var cv:MovieClip = new cView();
catNo += 1;
cv.name = "cv" + catNo;
cv.buttonMode = true;
if(catNo % 5 == 0)
{
catY += 137;
catX = -170;
cv.x = catX;
cv.y = catY;
}
else
{
cv.x = catX;
cv.y = catY;
catX += 112;
}
var imageLoader = new Loader();
imageLoader.load(new URLRequest(projectDP));
TweenLite.to(cv.cHolder, 1, {colorTransform:{tint:0x000000, tintAmount:0.8}});
cv.cHolder.addChild(imageLoader);
cv.ct.text = projectName;
projName.push(projectName);
this.addChild(cv);
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageProg);
function imageProg(e:ProgressEvent):void
{
loader.visible = true;
var imageLoaded:Number = e.bytesLoaded/e.bytesTotal*100;
loader.scaleX = imageLoaded/100;
}
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoad);
function imageLoad(e:Event):void
{
loader.visible = false;
}
First, don't put a function inside another function, this won't help for anything and is a bad habit :)
Declare two private variables:
var nImages:uint;
var loadedImages:uint;
Before the loop:
nImages = projectAttributes.length();
loadedImages = 0;
cv.visible = false;
and in the Event.COMPLETE listener:
function imageLoad(e:Event):void
{
loader.visible = false;
loadedImages++;
if (loadedImages == nImages)
{
cv.visible = true;
}
}
var count:int = 0;
var totalClips:int = 0;
cv.visible = false;
for each (var projectName:XML in projectAttributes)
{
++totalClips;
//trace(projectName);
var projectDP:XMLList = projectInput.project.(#name == projectName).displayP;
//trace(projectDP);
var cv:MovieClip = new cView();
catNo += 1;
cv.name = "cv" + catNo;
cv.buttonMode = true;
if(catNo % 5 == 0)
{
catY += 137;
catX = -170;
cv.x = catX;
cv.y = catY;
}
else
{
cv.x = catX;
cv.y = catY;
catX += 112;
}
var imageLoader = new Loader();
imageLoader.load(new URLRequest(projectDP));
TweenLite.to(cv.cHolder, 1, {colorTransform:{tint:0x000000, tintAmount:0.8}});
cv.cHolder.addChild(imageLoader);
cv.ct.text = projectName;
projName.push(projectName);
this.addChild(cv);
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageProg);
function imageProg(e:ProgressEvent):void
{
loader.visible = true;
var imageLoaded:Number = e.bytesLoaded/e.bytesTotal*100;
loader.scaleX = imageLoaded/100;
}
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoad);
function imageLoad(e:Event):void
{
++count;
if(count == totalClips){
cv.visible = true;
}
loader.visible = false;
}
}
So you might want to adapt things a little, in case I'm counting in the wrong spots etc for your implementation but as you can see the solution is simple, you count the total number of clips being processed for loading from the XML, then as the images are loaded and call the OnComplete callback, you increment another count until you've seen that you've loaded all processed images, and set the container to visible.