Why I can't display the variable on the textbox? AS3 - actionscript-3

I have textbox with instance_name power.
And I have variable called laserpower as int = 100.
I wanted to display the laserpower on power textbox.
I have used this, but it doesn't work.
var laserpower:int = 100;
.....
function onFrame(e:Event): void {
power.text = String(laserpower);
....
}
is there another way that I can make it?

There's no problem, the textField displays "100"...
import flash.events.Event;
import flash.text.TextField;
var laserpower:int = 100;
var power:TextField = power;
var debug:Boolean = false;
function onFrame(e:Event): void {
// trace the values one time only.
if(!debug){
trace ("event type = " + e.type);
trace ("power = " + power + " laserpower = " + laserpower);
debug = true;
// outputs:
// event type = enterFrame
// power = [object TextField] laserpower = 100
}
power.text = laserpower.toString();
}
this.addEventListener(Event.ENTER_FRAME,onFrame);
Tell us more about the code (on the timeline, on a separate class file?).
Where did you add the "addEventListener" method and what kind of Event do you're listening for?
What's the output if you add the trace() code?

Related

Prevent Movie Clip Overlapsing

I'm creating a screen saver which requires a movie clip to be loaded to the stage at a random position based on the size of the screen, then fade out (which I have all of the animation within a movie clip as tweens)
I've hit a road block and can't figure out how to prevent the movie clips from overlapsing on top of each other. If anything, I'd like for them to appear at another random spot that does not cause the overlapse.
here is all of the code for my project:
stop();
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
var greystoneLogos:Array = new Array ;
var countTimeArray:Array = new Array ;
var previousLogos:Array = new Array ;
var xpoint:int;
var ypoint:int;
function getNewSymbols()
{
previousLogos = new Array ;
greystoneLogos = new Array ;
var i:int;
for (i=0; i < 3; i++)
{
greystoneLogos[i] = new GreystoneLogo1();
greystoneLogos[i].width = 100;
greystoneLogos[i].height = 60;
addSymbolToStage(greystoneLogos[i],i*2000);
}
}
getNewSymbols();
function addSymbolToStage(currentLogo:MovieClip,waitTime:int)
{
var i3:int;
var i4:int;
var logoBoundaries:Array = new Array()
var XandY:Array = new Array()
for (i3=0; i3 < greystoneLogos.length; i3++)
{
if (greystoneLogos[i3] !== currentLogo)
{
xpoint = randomRange(this.stage.stageWidth - (currentLogo.width * 4.8));
ypoint = randomRange(this.stage.stageHeight - (currentLogo.height * 6.9));
logoBoundaries = getOffDimensions(currentLogo)
for (i4=0; i4 < logoBoundaries.length; i4++)
{
XandY = logoBoundaries[i4].split(":")
while ((xpoint <= (Number(XandY[0]) + Number(currentLogo.width * 4.8)) && xpoint >= (Number(XandY[0]) - Number(currentLogo.width * 4.8))) && (ypoint <= (Number(XandY[1]) + Number(currentLogo.height * 6.9)) && ypoint >= (Number(XandY[1]) - Number(currentLogo.height * 6.9)))){
xpoint = randomRange(this.stage.stageWidth - (currentLogo.width * 4.8));
trace(XandY[0] + " And " + (Number(currentLogo.width * 4.8)))
trace(xpoint + " And " + (Number(XandY[0]) + Number(currentLogo.width * 4.8)))
ypoint = randomRange(this.stage.stageHeight - (currentLogo.height * 6.9));
}
}
}
else
{
continue;
}
}
previousLogos.push(currentLogo);
currentLogo.x = xpoint;
currentLogo.y = ypoint;
stage.addChild(currentLogo);
currentLogo.gotoAndStop(1);
var countTime:Timer = new Timer(waitTime,1);
countTime.addEventListener(TimerEvent.TIMER, function(){
currentLogo.gotoAndPlay(1);
currentLogo.addFrameScript ( currentLogo.totalFrames - 1 , function(){
currentLogo.stop()
stage.removeChild(currentLogo)
if(stage.numChildren <= 1){
getNewSymbols();
}
}) ;
});
countTime.start();
}
function getOffDimensions(currentLogo:MovieClip){
var i3:int;
var tempArr:Array = new Array()
for (i3=0; i3 < greystoneLogos.length; i3++)
{
if (greystoneLogos[i3] !== currentLogo){
tempArr[i3]=greystoneLogos[i3].x +":"+ greystoneLogos[i3].y
}
}
return tempArr
}
function randomRange(max:Number, min:Number = 0):Number
{
return Math.random() * (max - min) + min;
}
There are also may be a handful of unused variables from multiple things I've been trying out.
The code that I posted, will make the movie clip appear at a random spot based on the last movie clip that came up. So let's say we have 3 movie clips (the user will be able to change how many of the clips get displayed) 1 appears at 0,0 the other at 400,400 and the last one appears at 10,10 because I have no way of saving the previous values to compare in the while loop.
I hope this clarifies it a tad more
EDIT:
Based on a function shown below, I've added this:
for (i3=0; i3 < greystoneLogos.length; i3++)
{
if (greystoneLogos[i3] !== currentLogo && greystoneLogos[i3] != null)
{
while(currentLogo.hitTestObject(greystoneLogos[i3]) == true){
xpoint = randomRange(this.stage.stageWidth - (currentLogo.width));
ypoint = randomRange(this.stage.stageHeight - (currentLogo.height));
i3 = 0
}
}else{
continue;
}
}
Which results in a rather bad loop as well as the logo's still overlap above each other
The quickest way I can think to solve this is to do a hit test (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#hitTestObject()) on the new MovieClip and if it returns true, run the placement code again
Ok, here's the implementation of this quickest way.
You can track your present displayObject by the .numChildren property. You don't even need an array of your logos or things. Let's say you have a function that adds new movieClip to your screen. It knows how many clips you can have (MovieClipDummy is just my testing class - it draws a circle with a specified radius. It should be replaced by your objects).
private function addAnotherMovieClip(): void {
if (_currentDummmiesCount < _dummmiesCount) {
var newDummy: MovieClipDummy = new MovieClipDummy(90);
addChild(newDummy);
//If we get a stackoverflow error (see below)
//we just remove our object from the screen as it will most likely just won't fit
if (checkForEmptySpace(newDummy) != "") {
removeChild(newDummy);
return;
}
} else {
//Do nothing or do something
}
}
It calls another function, checkForEmptySpace, which tries to place your movieclip so it won't overlap with other objects. Here it is:
private function checkForEmptySpace(newClip: Sprite): String {
//you should store your screen width somewhere.
//you can also call stage.stageWidth instead, but first make sure that you
//always have a link to the stage or it will throw an error
newClip.x = Math.random() * _screenWidth;
newClip.y = Math.random() * _screenHeight;
//===========================
//Important part - we try to check all the present children of our container
//numChildren is a property of the DisplayObjectContainer
for (var i: int; i < numChildren; i++) {
//We need a try here because we will get a StackOverflow error if there's no empty space left
try {
//We need to check if our current display object, received with getChildAt()
//is not the same as the one we've just added to the screen
//And if our new object intersects with ANY other object on the stage - we
//call THIS function once again.
//We do recursion because we can easily catch an error and remove this object from
//the screen
if (newClip != getChildAt(i) && newClip.hitTestObject(getChildAt(i))) {
//If our recursive function returns an error - we should pass it further
if (checkForEmptySpace(newClip) != "") {
return "error";
}
}
//The only error that can go here is stackoverflow error. So when we get one
//we return this error string
} catch (error: Error) {
trace(error);
return "error";
}
}
//We only return this empty string if we don't have stackoverflow error
//so there's possibly no space left for another movieclip
return "";
}
You can do it without recursion, but you will have to check for empty space with another logic.
And, you can do it more "professionally" by using Minkowski addition. You should consider storing an array of "boundary" points of your movieclips (let's say every movieclip is a rectangle) and when you add a new object to the screen, you calculate this Minkowsky addition. It will have some "free" spots on your screen which represent any possible coordinates of your new movieclip. It's pretty interesting to implement something like that because the accuracy will be phenomenal. But if you don't have time - just use that recursive placement function

Locale.loadLanguageXML() Won't work in external script

I have a script for multi-language-use working when added to the first frame of a timeline. However, when I try to adapt it to work in an external .as script, it throws a TypeError and I can't figure out why.
Here is the code that works in a timeline:
import fl.data.DataProvider;
import fl.text.TLFTextField;
import flash.text.Font;
import flashx.textLayout.elements.*;
import flashx.textLayout.formats.*;
//------------------
// CREATE TLFTEXTFIELD:
var field_001:TLFTextField = new TLFTextField();
field_001.x = 20;
field_001.y = 50;
field_001.width = 342
field_001.height = 54;
field_001.background = true;
addChild(field_001);
// Create text format
var format:TextLayoutFormat = new TextLayoutFormat();
format.fontFamily = "Arial";
format.fontSize = 36;
format.color = 0x666666;
// Apply the format
var textFlow:TextFlow = field_001.textFlow;
textFlow.hostFormat = format;
//------------------
// SETUP LOCALE OBJECT:
var languages:Object = new Object(); // Stores flags for loaded languages
var localeDefault:String = "ar"; // Default language
var locale:String = "ar"; // Current language selected in combobox
// Event handler for Locale object
function localeLoadedHandler(success:Boolean):void
{
if( success )
{
// Mark language as loaded and show localized string
languages[locale] = true;
field_001.text = Locale.loadStringEx("IDS_FIRSTFIELD", locale);
// field_002 is a field already on stage
field_002.text = Locale.loadStringEx("IDS_SECONDFIELD", locale);
}
}
// Load the default language...
Locale.setDefaultLang(localeDefault);
Locale.setLoadCallback(localeLoadedHandler);
trace("Locale.getDefaultLang() is: " + Locale.getDefaultLang());
Locale.loadLanguageXML(Locale.getDefaultLang());
Here is my adaptation to an external script and set up as the class for a standalone swf called "tempchild.swf" I want to open inside a parent swf at a later time:
package com.marsinc {
import fl.text.TLFTextField;
import flash.text.Font;
import flashx.textLayout.elements.*;
import flashx.textLayout.formats.*;
import flash.display.MovieClip;
import fl.lang.Locale;
public class tempchild extends MovieClip {
//------------------
// SETUP LOCALE OBJECT:
private var languages:Object; // Stores flags for loaded languages
private var localeDefault:String; // Default language
private var locale:String; // Current language selected in combobox
private var field_001:TLFTextField;
private var format:TextLayoutFormat;
public function tempchild()
{
// constructor code
languages = new Object();
localeDefault = "es";
locale = "es";
//------------------
// CREATE TLFTEXTFIELD:
field_001 = new TLFTextField();
field_001.x = 20;
field_001.y = 50;
field_001.width = 342
field_001.height = 54;
field_001.background = true;
addChild(field_001);
// Create text format
format = new TextLayoutFormat();
format.fontFamily = "Arial";
format.fontSize = 36;
format.color = 0x666666;
// Apply the format
var textFlow:TextFlow = field_001.textFlow;
textFlow.hostFormat = format;
// Load the default language...
Locale.setDefaultLang(localeDefault);
Locale.setLoadCallback(localeLoadedHandler);
trace("Locale.getDefaultLang() is: " + Locale.getDefaultLang()); // displays "es"
Locale.loadLanguageXML(Locale.getDefaultLang()); // this line returns an error
}
// Event handler for Locale object
private function localeLoadedHandler(success:Boolean):void
{
trace("running the loaded handler");
if( success )
{
// Mark language as loaded and show localized string
languages[locale] = true;
field_001.text = Locale.loadStringEx("IDS_FIRSTFIELD", locale);
//field_002.text = Locale.loadStringEx("IDS_SECONDFIELD", locale);
}
}
}
And this is the error in the output window:
TypeError: Error #1010: A term is undefined and has no properties.
at fl.lang::Locale$/loadXML()
at fl.lang::Locale$/loadLanguageXML()
at com.marsinc::tempchild()
Been digging around for an answer for a couple days now and I am stuck. Any help is greatly appreciated. Thanks!
--Kevin
You can make it .as file in one of (at least) two ways
1) copy paste all exactly as it is to .as file and do:
include "[path]filename.as"
2) change the code to be a class
- make field_001, format, textFlow, languages, localeDefault, locale as public vars
- insert all code in a function named "init"
- add the "localeLoadedHandler" as a function
- click on your stage and change in the properties panel the stage's class to the new class
Good Luck!!

Flash Builder 4 + Flash Professional + FlashVars != WORKING

I have a Flash Builder 4 project that's hooked up to a Flash Professional CS5 FLA.
I do NOT use MXML, and all code is handled directly in Flash Builder. (Flash itself is used simply for the library, and its easier for our artists to use)
Everything's been going along without a hitch, everything runs off of dynamically generated XML from the site the SWF is embedded to. But up until now I've had the XML path hardcoded in the actionscript. I wish simply to not make it so.
I have followed minimum 45 tutorials on getting FlashVars into FB4/As3, and quite simply nothing seems to be working.
Old school < embed > method, using < object > method, and even using swfObject method, simply I cannot seem to access these flashvar properties.
here's the html that i currently have now:
<script>
var flashvars = {
xml: "/mapsystem/xml"
}; // yes that is definitely the correct path, its the same value as when it was hardcoded
$(function() {
swfobject.embedSWF("/flash/map.swf", "map", "960", "885", "10.0.0", "expressInstall.swf", flashvars);
});
</script>
<div id="map">
swfObject Aint Working
</div>
Heres the actionscript (this is in my Document class, first thing)
package
{
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import src.GlobalStage;
import src.Map;
import src.Styles;
public class map extends GlobalStage
{
public var xmlDoc = "map.xml";
public function map()
{
var test:TextField = new TextField();
test.x = 50;
test.y = 50;
test.autoSize = TextFieldAutoSize.LEFT;
test.text = "XML Doc: ";
this.addChild(test);
var test2:TextField = new TextField();
test2.x = 50;
test2.y = 80;
test2.multiline = true;
test2.border = true;
test2.autoSize = TextFieldAutoSize.LEFT;
test2.text = "Parameters: \n";
test2.appendText("Total Parameters: ");
this.addChild(test2);
var _params:Object;
if ( this.loaderInfo.parameters.length != null ) {
_params = this.loaderInfo.parameters;
} else {
// run alt code to init
}
for(var pItem:String in _params) {
test2.appendText("Name: " + pItem + " :: " + _params[pItem] + "\n" );
}
if(_params['xml'] != null) xmlDoc = _params['xml'];
test.appendText(xmlDoc);
var map:Map = new Map(xmlDoc);
Now, when i run this on my local test, nothing shows up as per expected, but when it comes to being on the site itself, with a passed flashvar, the xmlDoc remains "map.xml", my counter tells me there are 0 parameters, and of course nothing shows up in my list of parameters.
I have spent 8 hours trying to get this to work, quite frankly I'm losing hair and sleep over this.
loaderInfo.parameters is an Object, and so the condition in this if statement is never likely to be true (unless your flashVars had a param named 'length'):
if (this.loaderInfo.parameters.length != null) {
So instead of checking if the length is not null, just check if the parameters are not null:
if (loaderInfo.parameters) {
loaderInfo.parameters is an object, and it is never null. What you must do is check for your flashvar's existence like this:
if (loaderInfo.parameters.xml)
{
var xmlPath:String = loaderInfo.parameters.xml
// start using xml
}
else
// run alt code to init
}

How can I make this Flash code work in IE when it's cached?

I have a flash file here, when the flash plays, it works fine, but in IE and if the flash was already loaded once and is now cached, it freezes up. After digging super deep on the internet I was able to find out the following:
There are a bunch of known bugs in
flash 9 and 10, one of those being an
issue with the Event.COMPLETE not
being fired from the main stage when
loading from cache when it's embedded
WMODE = "transparent" I'm not sure if
that's your issue, but it's worth
looking into. I've heard of a few
workarounds to the problem. One of
them being, not listening for for
progress or complete events at all and
just using a timed loop like
ENTER_FRAME or TIMER to watch the
bytesLoaded/bytesTotal.
My WMODE is window, but this makes the most sense to me. The loadText never gets set which tells me its not entering swfProgressHandle function. However the problem is I only wrote half this flash (everything inside init) in conjunction with someone else, but that other person I cannot get in contact with anymore. I am fairly new to flash so really don't know how to take his loading code and make it only run off timer events instead of progress and complete events (as said in the above quote) so that it will work in IE when cached. Can anyone help me on this? Most of the code is fine, it's just the beginning where those progress and complete handlers are for loading stuff that appears to be causing the issue.
package
{
//---Imports---
import flash.display.*;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.*;
import flash.events.Event;
import flash.events.*;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.utils.Timer;
import flash.utils.*;
import flash.text.Font;
public class FohLoader extends Sprite
{
//create and start load bar
private var loadBar:Sprite = new Sprite();
private var loadText:TextField = new TextField();
private var loadBarBg:Graphics = loadBar.graphics;
//load XML data
private var xmlLoader:URLLoader = new URLLoader();
private var xmlData:XML = new XML();
private var _queue:Array; //holds data objects of items to be loaded
private var _index:int; //the current item in the _queue
private var _images:Array; //holds DisplayObjects of the loaded images
public function FohLoader()
{
_queue = new Array();
_images = new Array();
_index = 0;
//waits for the stage to be created
addEventListener(Event.ADDED_TO_STAGE, stageReadyHandle);
}
private function stageReadyHandle(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, stageReadyHandle);
loadBarBg.lineStyle();
loadBarBg.beginFill(0x5a96c5, 1);
loadBarBg.drawRect(0, 0, 5, 10);
loadBarBg.endFill();
loadBar.x = (stage.stageWidth - 500)/2;
loadBar.y = 30;
loadBar.width = 5;
loadBar.height = 10;
this.addChild(loadBar);
loadText.x = (stage.stageWidth - 0)/2;
loadText.y = 50;
this.addChild(loadText);
//I have no idea if this crap works
//but you would have to do something like this if you want to keep your project to one swf file.
this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, swfProgressHandle);
}
private function swfProgressHandle(e:ProgressEvent):void
{
//assumes you want the loadbar to be 500px at 100%
var getPercent:Number = bytesLoaded / e.bytesTotal;
trace(bytes_loaded + " of " + bytes_total + " loaded");
loadBar.width = getPercent * 150; //changed 500 to 150
loadText.text = String(Math.round(getPercent * 30) + "%"); //changed 100 to 30
if (e.bytesLoaded / e.bytesTotal >= 1)
{
e.target.removeEventListener(ProgressEvent.PROGRESS, swfProgressHandle);
loadXml();
}
}
private function loadXml()
{
xmlLoader.addEventListener(Event.COMPLETE, ParseXML);
xmlLoader.load(new URLRequest("flash.xml"));
}
private function ParseXML(e:Event):void
{
e.target.removeEventListener(Event.COMPLETE, ParseXML);
flashInputs = new XML(e.target.data);
//declare all XMl variables, terrible way to do it though
var imageURLList:XMLList = flashInputs.image_area.image.image_url;
var firmCount:XMLList = flashInputs.count_area.total_firms;
var quoteMsg:XMLList = flashInputs.quote_area.quote.quote_text;
var quoteOwner:XMLList = flashInputs.quote_area.quote.quote_owner;
var imageURL:XMLList = flashInputs.image_area.image.image_url;
var imageText:XMLList = flashInputs.image_area.image.image_text;
var quoteMsg0:XML = quoteMsg[0];
var quoteMsg1:XML = quoteMsg[1];
var quoteMsg2:XML = quoteMsg[2];
var quoteMsg3:XML = quoteMsg[3];
var quoteMsg4:XML = quoteMsg[4];
var quoteMsg5:XML = quoteMsg[5];
var quoteMsg6:XML = quoteMsg[6];
var quoteOwner0:XML = quoteOwner[0];
var quoteOwner1:XML = quoteOwner[1];
var quoteOwner2:XML = quoteOwner[2];
var quoteOwner3:XML = quoteOwner[3];
var quoteOwner4:XML = quoteOwner[4];
var quoteOwner5:XML = quoteOwner[5];
var quoteOwner6:XML = quoteOwner[6];
var imageText0:XML = imageText[0];
var imageText1:XML = imageText[1];
var imageText2:XML = imageText[2];
var imageText3:XML = imageText[3];
var imageText4:XML = imageText[4];
var imageText5:XML = imageText[5];
var imageText6:XML = imageText[6];
var imageURL0:XML = imageURL[0];
var imageURL1:XML = imageURL[1];
var imageURL2:XML = imageURL[2];
var imageURL3:XML = imageURL[3];
var imageURL4:XML = imageURL[4];
var imageURL5:XML = imageURL[5];
var imageURL6:XML = imageURL[6];
//loops through the imageURL array and adds each item to the queue
for each(var img:XML in imageURL)
{
addItem(String(img));
}
//loads the first item in the queue
loadItem();
}
//creates a new loader for the item
//adds a data object holding the item path and loader into the queue
private function addItem(path:String):void
{
var loader:Loader = new Loader();
_queue.push({loader:loader, path:path});
}
private function loadItem():void
{
_queue[_index].loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgCompleteHandle);
_queue[_index].loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, IOErrorHandle);
_queue[_index].loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imgProgressHandle);
_queue[_index].loader.load(new URLRequest(_queue[_index].path));
}
//checks the progress of each image, and increases the width of the load bar
private function imgProgressHandle(e:ProgressEvent):void
{
var perc:Number = e.bytesLoaded / e.bytesTotal;
//this line assumes you are loading 6 images, and want the loadbar to end up at 500px
//it also assumes the bar has already reached 30% (150px) from loading the swf
loadBar.width = 150 + (_index * (350 / 6)) + ((350 / 6) * perc);
//so the swf's 150 + (how many images have alrady loaded * the width each image needs to affect the bar) +
//(same thing * percent of current image loaded)
//sounds right, might have to mess with that.
}
//this just stops flash from outputting an error if the image fails to load
private function IOErrorHandle(e:IOErrorEvent):void
{
e.target.removeEventListener(Event.COMPLETE, imgCompleteHandle);
e.target.removeEventListener(IOErrorEvent.IO_ERROR, IOErrorHandle);
trace("Error handled, sir.");
trace("The problem was that, " + e);
}
private function imgCompleteHandle(e:Event):void
{
e.target.removeEventListener(Event.COMPLETE, imgCompleteHandle);
e.target.removeEventListener(ProgressEvent.PROGRESS, imgProgressHandle);
e.target.removeEventListener(IOErrorEvent.IO_ERROR, IOErrorHandle);
//adds the image to the _images array
_images.push(e.target.content);
//increments the load counter
_index++;
//checks to see if the queue is finished or not
if (_index < _queue.length)
{
trade("Not done loading, loading another item");
loadItem();
}
else
{
_index = 0;
_queue = [];
killLoadBar();
init();
}
}
private function killLoadBar()
{
this.removeChild(loadBar);
this.removeChild(loadText);
}
If you dont mind the flash loading every time and not using the cache you could just append a cache breaker to the swf url.
Any random thing will do.
Here's a example using swfobject (http://code.google.com/p/swfobject/)
<script type="text/javascript">
var flashvars = {};
var params = {};
var attributes = {};
swfobject.embedSWF("myContent.swf?rand="+Math.random(), "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);
</script>
This should work around any IE cache bugs.
If you still get the error with this, then it's should not be cache related.
After taking a quick look at this, I can see what might be happening.
You listen for ADDED_TO_STAGE.
You handle ADDED_TO_STAGE and then start listening for PROGRESS.
You then set the loadText, and load the XML if progress is "done".
The problem here seems to be the "done" part and the progress handling. First, the
loaderInfo object has a COMPLETE event. Why not use it? (http://livedocs.adobe.com/flex/3/langref/flash/display/LoaderInfo.html)
Then you could skip the whole bytesLoaded/bytesTotal check.
Where I think the applicatation might be freezing is when the loaderInfo has cached resources and skips the "PROGRESS" step altogether. Then you would never get into the LoadXML code, and never, therefore, parse the xml.
You can install firebug in Firefox and check whether you're even attempting to load the XML file using the "net" tab. (or use a tool like filemon).

How can I get the background color of a loaded swf file?

I'm loading an swf file into my main application using URLLoader, I want to get the background color of the loaded swf file. ( I heard that one solution wold be reading the byte code of the loaded swf )
Yes, You need to look into binary swf data. Here is brief description of swf format. And this is a little detail about different kind of tags. Your requirement is to find out SetBackgroundColor tag(tag type = 9), which commonly is either first or second tag of the swf. Bytes in swf file follows little endian order, so you need to be careful while reading the data. And mostly they will be compressed(first three bytes will be "CWS") so from 9th bytes onwards (including 9th), all data needs to be decompressed (ByteArray.decompress) before processing.SomeExample code :) package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
public class Test1 extends Sprite{
private var stream:URLStream;
public function Test1():void {
stream = new URLStream();
stream.load(new URLRequest("some.swf"));
stream.addEventListener(Event.COMPLETE, onComplete);
}
private function onComplete(e:Event):void {
var bytes:ByteArray = new ByteArray();
bytes.endian = Endian.LITTLE_ENDIAN;
stream.readBytes(bytes, 0, 8);
var sig:String = bytes.readUTFBytes(3);
trace("SIG = " + sig);
trace("ver = " + bytes.readByte());
trace("size = " + bytes.readUnsignedInt());
var compBytes:ByteArray = new ByteArray();
compBytes.endian = Endian.LITTLE_ENDIAN;
stream.readBytes(compBytes);
if (sig == "CWS") {
compBytes.uncompress();
}
var fbyte = compBytes.readUnsignedByte();
var rect_bitlength = fbyte >> 3;
var total_bits = rect_bitlength * 4;
var next_bytes = Math.ceil((total_bits - 3)/ 8);
for(var i=0; i<next_bytes; i++) {
compBytes.readUnsignedByte();
}
trace("frameRate = " + compBytes.readUnsignedShort());
trace("frameCount = " + compBytes.readUnsignedShort());
while(true) {
var tagcodelen:Number = compBytes.readUnsignedShort();
var tagcode:Number = tagcodelen >> 6;
var taglen:Number = tagcodelen & 0x3F;
trace("tag code = " + tagcode + "\tlen = " + taglen);
if (taglen >=63) {
taglen = compBytes.readUnsignedInt();
}
if(tagcode == 9) {
trace("found background color");
trace("color is: RED=" + compBytes.readUnsignedByte() +", GREEN = " + compBytes.readUnsignedByte() + ", BLUE = " + compBytes.readUnsignedByte());
break;
}
compBytes.readBytes(new ByteArray(), 0, taglen);
//break;
}
}
}
}
You SWF file has to pass it to a web page with JS.
getURL("javascript:setColour(" + DESIRED COLOUR + ")");
The "setColour" function of course must do what you want it to do.