Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




Function / Loader Problem



95% of this code is working correctly, except the last 7 lines. I have a need to be able to uniquely name each mc and track its position and other individual attributes, and for this reason I went with an array. The mc's need to initially be all off the screen (x:20, y:20 in this example - I will move them completely off later) except mc1 which will be in a designated spot, but this part of the code is not working (see last ~7 lines). Any thoughts?


ActionScript Code:
_root.Total_Parts = 4;var mcl:MovieClipLoader = new MovieClipLoader();var listener:Object = new Object();mcl.addListener(listener);listener.onLoadInit = function(mc:MovieClip) {    mc.origSize = {w:mc._width, h:mc._height};    if (mc._height>Toolbox._height) {        mc._height = Toolbox._height;        mc._width = Toolbox._height*(mc.origSize.w/mc.origSize.h);        mc.scaledSize = {w:mc._width, h:mc._height};    }    if (mc._width>Toolbox._width) {        mc._width = Toolbox._width;        mc._height = Toolbox._width*(mc.origSize.h/mc.origSize.w);        mc.scaledSize = {w:mc._width, h:mc._height};    }    if ((mc._width<Toolbox._width) && (mc._height<Toolbox._height)) {        mc.scaledSize = {w:mc._width, h:mc._height};    }    mc._x = Toolbox._x+((Toolbox._width/2)-(mc.scaledSize.w/2));    mc._y = Toolbox._y+((Toolbox._height/2)-(mc.scaledSize.h/2));    mc.centered = {horiz:mc._x, vert:mc._y};    mc.placement = "In_Toolbox";    mc.ToolboxStatus = "Not_Current_View";    mc.visibility = "false";    mc.onPress = function() {        this._height = mc.origSize.h;        this._width = mc.origSize.w;        this.startDrag(false, 0, Main_Stage._y, (945-(mc.origSize.w)), ((Main_Stage._y+Main_Stage._height)-mc.origSize.h));    };    mc.onRelease = function() {        stopDrag();        if ((this.hitTest(Non_Stage) == true) && (this.placement == "On_Stage") && (this.ToolboxStatus != "Current_View")) {            with (mc) {                this._width = mc.scaledSize.w;                this._height = mc.scaledSize.h;                this._x = 20;                this._y = 20;                this.placement = "In_Toolbox";            }        }        if ((this.hitTest(Non_Stage) == true) && (this.placement == "On_Stage") && (this.ToolboxStatus == "Current_View")) {            with (mc) {                this._width = mc.scaledSize.w;                this._height = mc.scaledSize.h;                this._x = mc.centered.horiz;                this._y = mc.centered.vert;                this.placement = "In_Toolbox";            }        } else {            trace("width:"+this.origSize.w);            trace("height:"+this.origSize.h);            mc.placement = "On_Stage";        }    };};var Part:Array = new Array();for (var i:Number = 1; i<=_root.Total_Parts; i++) {    var Part_clip:MovieClip = createEmptyMovieClip("PNG_Loaded_"+i, i);    mcl.loadClip("PNG/Part_"+i+".png", Part_clip);    Part[i] = Part_clip;}_root.j = 1;// below not workingfor (var i:Number = 1; i<=_root.Total_Parts; i++) {    Part[i]._x = 20;    Part[i]._y = 20;    Part[i].ToolboxStatus = "Not_Current_View";}Part[1]._x = Part[1].centered.horiz;Part[1]._y = Part[1].centered.vert;Part[1].ToolboxStatus = "Current_View";



ActionScript.org Forums > ActionScript Forums Group > ActionScript 2.0
Posted on: 06-22-2007, 07:01 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Please Help W/ Pre-Loader Function
Not sure if this should be posted in the Newbie forum or not, I'm kind of embarassed I spent the last few days working on this, but still couldn't get it to work :-(

I'm trying to preload my movie, 3 scenes, the first being a 2 frame preloader. The 2nd frame is:

if (_root.getBytesLoaded() == _root.getBytesTotal()) {
nextScene ();
} else {
gotoAndPlay (1);
}

When I use the "nextScene()" method, it opens the next scene, but doesn't play anything, it just sits there (showing only the background), doing nothing.

If I change "nextScene()" to the actual scene:

gotoAndPlay ("intro", 1);

It will play only the first frame from the 2nd scene, but that scene is a dynamic text intro and it only works the "W" in the "Welcome to my web site", then gets into the main 3rd scene.

Frame 1 of 2nd scene:
text = "Welcome to My Web Site!!!";
i = 1;
showed = 0;
max = length(text);
kerning = "15";
size = "30";
setProperty ("char", _visible, "0");

My question is: Which method should I be using, and how do I get the preloader scene to load, then move into the 2nd scene and play it fully from the beginning? I know it works right, b/c when I just play the 2nd and 3rd scenes they work great, just not with the preloader.

Any help is appreciated, thanks!!!

Loader In A Function Problem
Code:
package classes{

Code:

import flash.display.MovieClip;

import flash.display.Loader;
import flash.events.Event;
import flash.events.ErrorEvent;
import flash.events.MouseEvent;
import flash.net.URLRequest;
public class BigPic extends MovieClip {
public var path:String;
public var shir:int;
public var viso:int;
public var picReq:URLRequest;
public var picLoader:Loader = new Loader();
public function BigPic() {
picLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, zaComplete);
picLoader.contentLoaderInfo.addEventListener(ErrorEvent.ERROR, zaGreshka);
}
private function zaComplete(ev:Event) {
var mc = picLoader.content;
var shi:int = shir;
var vis:int = viso;
if (mc.width>shi || mc.height>vis) {
var ro:Number = shi/vis;
var r:Number = mc.width/mc.height;
if (r>ro) {
mc.width = shi;
mc.height = shi/r;
} else {
mc.height = vis;
mc.width = vis*r;
}
}
mc.x = (this.width/2) - (mc.width/2);
mc.y = (this.height/2) - (mc.height/2);
this.addChild(mc);
}
private function zaGreshka(ev:ErrorEvent) {
picLoader.load(picReq);
}
public function comeon(req:String) {
picReq = new URLRequest(req);
picLoader.load(picReq);
}
}
}



When I call the function comeon(path) from another class it says:


ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::Loader/flash.display:Loader::_load()
at flash.display::Loader/load()
at classes::BigPic/comeon()
at classes::BrandPix/::zaClick()
The problem is because of this line :
picLoader.load(picReq);
Any ideas how to solve this ?

Pre-loader Problem With .loadMovie Function
Hi all, I would really appreciate some help with this.

I've created a flash with 6, 7 frames. The first couple of frames are selection queries, each will set up values for variables in root. The last frame has 2 main loop in it; using the selection made in the previous frames, it search through an xml file and create an array. It than uses the array to load various flash files on to the stage (using instance.loadMovie).
Here is my problem, when the flash is search through the xml file and loading other flashs on the stage it freezes. The clock froze until everything get loaded and it jumps to the correct time again, you can't click on any of the buttons...etc. I'm considering to add a pre-loader in the flash but, I'm not sure it'll help if that last frame freezes while is loading anyway. Can anybody explain to me how this happen and if there is anyway of going around this.

Here is some extra info:

1st frame ~ 100K
2nd frame ~ 10K
3rd frame ~ 8K
4th frame ~ 30K
5th frame ~ 8K
6th frame ~ 5K
7th frame ~ 8K

XML file ~ 14K
external flashs ~ 90K to 150K each

Finding The Problem In My Loader Function
Hi
I'm having problems finding the error in my image loader loop - can you have a look and see if you can spot the problem, please?

What's supposed to happen: the first function "triggerImageLoader()" creates the first image holder in the stack using the variable "_level0.nextMainImageNumber" then makes it invisible and creates another clip inside that (i can't remember the reason for this, lol). It then triggers the load function and sets the interval "bytesIndicator()" to follow the load process. When the interval has detected that the image has loaded it increments "_level0.nextMainImageNumber" and starts the whole process again until it reaches the number of images defined in "_level0.numImages".

What happens: the functions repeat the correct number of times, outputting 0 bytes each time, but in about 1 second and then stop, even though the first image hasn't even loaded. I've checked this on the server - it outputs that the 16th image has been loaded while, in reality, image number 2 hasn't finished loading.

here's the code - I've commented it as much as i can

code: //*********************************************//
// CREATE THE MAIN IMAGE LOADER CLIPS //

// create a stack of clips and make them invisible then start loading the first big image

var nextMainImageNumber = 1; // this number is incremented each time a big image has loaded
var byteLoad = 0; // set the bytesLoaded var
var byteTotal = 0; // set the bytesTotal var

// create clips
function triggerImageLoader(){
// if not all the images have been loaded yet
if(_level0.nextMainImageNumber<=_level0.numImages) {
// start the next loading procedure
// create the empty clips
_level0.imageLoaderMain.createEmptyMovieClip("hold er"+_level0.nextMainImageNumber, _level0.nextMainImageNumber);
// make the empty clips invisible
_level0.imageLoaderMain["holder"+_level0.nextMainImageNumber]._visible = false;
_level0.imageLoaderMain.holder1._visible = true;
trace("clip "+_level0.nextMainImageNumber+" created");
// create jpg clips to receive the jpgs
_level0.imageLoaderMain["holder"+_level0.nextMainImageNumber].createEmptyMovieClip("jpg",0);
// start loading the main image
loadMovie(_level0.baseFolder+"/"+_level0.nextMainImageNumber+".jpg", _level0.imageLoaderMain["holder"+_level0.nextMainImageNumber].jpg);
// start the bytes loaded checker interval
_level0.bytesIndicatorInterval = setInterval(_level0.bytesIndicator,16);
}else{
trace("finished loading main images");
}
}

// interval that checks the loading of each jpg and starts off the next one by calling triggerImageLoader()
function bytesIndicator(){
// get the number of bytes loaded of the main image
_level0.byteLoad = _level0.imageLoaderMain["holder"+_level0.nextMainImageNumber].jpg.getBytesLoaded();
trace("loaded = " + _level0.byteLoad);
// get the total byte size of the main image
_level0.byteTotal = _level0.imageLoaderMain["holder"+_level0.nextMainImageNumber].jpg.getBytesTotal();
trace("total = " + _level0.byteLoad);
// display the bytes loaded as a percentage ...
_level0.percentVar = Math.ceil((_level0.byteLoad/_level0.byteTotal) * 100);
_level0.ouputBytes.percentText.text = _level0.percentVar;
// check if the image has finished loading
if(_level0.byteLoad >= _level0.byteTotal){
trace("image "+_level0.nextMainImageNumber+ "loaded");
trace(_level0.percentVar+" %");
_level0.counter.gotoAndStop(_level0.nextMainImageN umber);
// stop the bytes loaded checker interval
clearInterval(_level0.bytesIndicatorInterval);
// increase the image number by one to load the next image
_level0.nextMainImageNumber += 1;
// start the load procedure of the next big image
triggerImageLoader();
}
}



It's probably something really simple but i just can't see it

edited with AS tags for clarity
gparis

Problem Accessing Loader From Within A Function
I am trying to make a compilation of swf files loaded externally. When one finishes, the next in the Array should play, pretty simple really, but i'm having troubles.

Here is my code...


Code:
var loaded_swf:MovieClip;
var videos:Array = new Array("video.swf", "video2.swf", "video3.swf");
var i:int = 0;
var url:URLRequest = new URLRequest(videos[i]);
var ldr:Loader = new Loader;
ldr.load(url);

function swfLoaded(e:Event):void
{
loaded_swf = e.target.content;
addChild(loaded_swf);

trace("swf loaded");

loaded_swf.video_mc.addEventListener("SWFSTOP", function(e:Event)
{
removeChild(loaded_swf);
i++;
ldr.load(url)
trace(i);
}
);
}

ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, swfLoaded);
The first swf plays fine. It reaches the last frame which has the SWFSTOP code inside it. The SWFSTOP code then runs fine until it reaches "ldr.load(url)". I get this error message...


Code:
swf loaded
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::Loader/_load()
at flash.display::Loader/load()
at MethodInfo-1105()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at video_fla::video_mc_1/frame209()

Ultimate SWF/IMAGE Loader Function
Here is my ultimate swf/image loader, I'm just simplifying everything down to a four variable function (basically). I need help with some of the code, the width and height will not render because the stupid checkProgress function that I don't know how to get around.


If anyone can fix this function it would benefit this forum, me and the web!



ActionScript Code:
MovieClip.prototype.imageMC = function(imageName:String, imageURL:String, imageWidth:Number, imageHeight:Number, maintainAspect:Boolean) {
    var imageHolder:String = imageName+"_imageHolder";
    this.createEmptyMovieClip(imageName, this.getNextHighestDepth());
    this[imageName].createEmptyMovieClip(imageHolder, this[imageName].getNextHighestDepth());
    var mcLoader:MovieClipLoader = new MovieClipLoader();
    var listener:Object = new Object();
    mcLoader.addListener(listener);
    mcLoader.loadClip(imageURL, this[imageName][imageHolder]);
    var interval:Object = new Object();
    interval.id = setInterval(checkProgress, 100, mcLoader, this[imageName][imageHolder], interval);
    [b]MovieClip.prototype.checkProgress = function(mcLoader:MovieClipLoader, image:MovieClip, interval:Object):Void  {
        var progress:Object = mcLoader.getProgress(this[imageName][imageHolder]);
        if (progress.bytesLoaded == progress.bytesTotal) {
            trace( "hello" );
            this[imageName][imageHolder].lineTo(this[imageName][imageHolder]._width, this[imageName][imageHolder]._width);
            if (maintainAspect == undefined || maintainAspect == false) {
                this[imageName][imageHolder]._width = imageWidth;
                this[imageName][imageHolder]._height = imageHeight;
            }
            clearInterval(interval.id);
        }
    };[/b]
};
// Example
imageMC("cool2", "Port3.swf", 200, 200);


Cheers Mates
Nick

Problem Accessing Loader From Within A Function
I am trying to make a compilation of swf files loaded externally. When one finishes, the next in the Array should play, pretty simple really, but i'm having troubles.

Here is my code...


Code:
var loaded_swf:MovieClip;
var videos:Array = new Array("video.swf", "video2.swf", "video3.swf");
var i:int = 0;
var url:URLRequest = new URLRequest(videos[i]);
var ldr:Loader = new Loader;
ldr.load(url);

function swfLoaded(e:Event):void
{
loaded_swf = e.target.content;
addChild(loaded_swf);

trace("swf loaded");

loaded_swf.video_mc.addEventListener("SWFSTOP", function(e:Event)
{
removeChild(loaded_swf);
i++;
ldr.load(url)
trace(i);
}
);
}

ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, swfLoaded);
The first swf plays fine. It reaches the last frame which has the SWFSTOP code inside it. The SWFSTOP code then runs fine until it reaches "ldr.load(url)". I get this error message...


Code:
swf loaded
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::Loader/_load()
at flash.display::Loader/load()
at MethodInfo-1105()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at video_fla::video_mc_1/frame209()

Generic Text File Loader Function
In AS3 I am trying to create a function that will accept a source string that contains the name of a text file and a target string to load the text into when it is loaded. I have:
function processText(tSource:String,tTarget:String):void {
var textReq:URLRequest = new URLRequest(tSource);
var textLoad:URLLoader = new URLLoader();
textLoad.load(textReq);
textLoad.addEventListener(Event.COMPLETE, textReady);
}

I don't know how to write the textReady handler so that it can access the target string.

Any help would be appreciated.

The problem is that the textReady function

External CSS And Text File Loader As A Function
I am trying to make use of an external style sheet and text file loader as a function. However, it appears that somewhere along the line a variable is perhaps over riding another one. I don't quite have the grasp of this code, and that's why I probably can't detect where my error is.

The following function works when I perform the first 'storyLoader' call. But the second 'storyLoader' call returns an "undefined" in both text fields.

Here is the code:

// Code begin

storyLoader(feature1, "featurestory1.txt");
storyLoader(feature2, "featurestory2.txt");

function storyLoader(thefeature, thefile) {
var format = new TextField.StyleSheet();
var path = "feature.css";
format.load(path);
format.onLoad = function(loaded) {
if (loaded) {
thefeature.story.styleSheet = format;
thefeature.links.styleSheet = format;
myLoadVar = new LoadVars ();
myLoadVar.load(thefile)
myLoadVar.onLoad = function (success){
if (success == true) {
thefeature.story.variable = "story"
thefeature.story.htmlText=myLoadVar.story;
thefeature.links.variable = "links"
thefeature.links.htmlText=myLoadVar.links;
}
}
} else {
output.text = "Error loading CSS file!";
}
}
}

// Code end

External CSS And Text File Loader As A Function
I am trying to make use of an external style sheet and text file loader as a function. However, it appears that somewhere along the line a variable is perhaps over riding another one. I don't quite have the grasp of this code, and that's why I probably can't detect where my error is.

The following function works when I perform the first 'storyLoader' call. But the second 'storyLoader' call returns an "undefined" in both text fields.

Here is the code:

// Code begin

storyLoader(feature1, "featurestory1.txt");
storyLoader(feature2, "featurestory2.txt");

function storyLoader(thefeature, thefile) {
var format = new TextField.StyleSheet();
var path = "feature.css";
format.load(path);
format.onLoad = function(loaded) {
if (loaded) {
thefeature.story.styleSheet = format;
thefeature.links.styleSheet = format;
myLoadVar = new LoadVars ();
myLoadVar.load(thefile)
myLoadVar.onLoad = function (success){
if (success == true) {
thefeature.story.variable = "story"
thefeature.story.htmlText=myLoadVar.story;
thefeature.links.variable = "links"
thefeature.links.htmlText=myLoadVar.links;
}
}
} else {
output.text = "Error loading CSS file!";
}
}
}

// Code end

Loading A SWF File In A Loader Where Button In Seperate Swf, With Function To Load
Well this is my problem. I have one big website in flash, and I'm trying to make it faster, by making lots of external swf files that opens in a loader. So I came to a point where my brain cannot think of any solution; I have the site with the loader (myLoader, mx.control Loader) and I load one external .swf file which have a button in itself. (many buttons actually). So I want to make it, if I click on one of those buttons, that myloader loads another .swf file... and replace the file that was there (with buttons)..

Make it clear, in the folder there is a website (SITE3.swf),... loads a file (about.swf) and there is third file (technologies.swf) that needs to be loaded but over about.swf onto SITE3.swf

Double Loader & One Instance Level Loader
Just sharing what I figured out.(which wasn't much but hey figured I'd post it anyway)

TASK1
I needed a preloader to load two seperate MC's into levels 1&2. Level 2 contains the interface which would change the MC on level 1.

TASK2
Once these two initial movies were loaded I then needed a single instance of a preloader that I could call upon for each subsequently loaded movie on level 1.

All the MC's have linkages so standard loaders would not start until 30%-40% of the MC was loaded.

I used a couple of files from oldnewbie.


http://odin.prohosting.com/~oldnew/f...ng/preload.zip


For TASK 1 I used the code from the above file but modified it a little.
I simply duplicated every line that referred to containerMC and called it containerMC2.Then at the end of the script instead of loading a single movie into level 0, I loaded the 2 MC's I had previously loaded into the containers onto levels 1 & 2. There's probably a much better way to do this - but it works

IF ANY OF YOU HAVE A BETTER SUGGESTION OR A WAY TO PRELOAD 2 MOVIES WITH LINKAGES INTO SEPERATE LEVELS WHERE THE PRELOADER MOVES FROM "Currently preloading movie 1" to "Currently preloading movie 2" WOULD BE AWESOME.

For TASK 2 I used another file from oldnewbie (though I can't recall which thread I found it in).

It's a One Instance Preloader for all subsequently loaded swf's.

The button code for loading a movie:

on(release) {
_root.preloader.gotoAndStop(2);
loadMovieNum("One.swf",1)
}


The preloader code:

FRAME 1

stop();

FRAME 2 (where the symbols are - same symbols as in the .zip file above)

this.onEnterFrame=function(){
//trace the percentage of the movie that has loaded
percent=(_level1.getBytesLoaded()/_level1.getBytesTotal())*100;

if(!isNan(percent)){
//trace(Math.ceil(percent)+"% loaded");
if (percent == 0) {
percent_display = "";
} else {
percent_display = Math.ceil(percent) + "% LOADED.";
}
this.loadbar._visible = true;
this.loadbar._xscale = percent;
if (percent > 1) {
this.reelmc._visible = true;
}
_level1.stop();
}
if(percent == 100){
this.gotoAndStop(1);
delete this.onEnterFrame;
this.reelmc._visible = false;
percent_display = "";
this.loadbar._visible = false;
_level1.play();
}
}
stop();

That's it. If you can use it, great.

Simple Loader Fails When Loading In An .swf Containing The Loader.
Sorry for the complicated topic. I got a .swf that loads in other .swfs. Rather than figuring out how to make a loader for loading .swfs I thought I'd just use a simple loader in the .swf I'm loading.

However, it doesn't work. It starts fully loaded but doesn't finish. Heres the AS:

ActionScript Code:
_root.stop();
PercentLoaded = _root.getBytesLoaded()/_root.getBytesTotal()*100;
if (PercentLoaded != 100) {
    bar._xscale = PercentLoaded;
} else {
    _root.play();
}

Anyone got a clue? Or would anyone be willing to point me in the direction for a very simple .swf loader.

thanks!

Simple Loader Fails When Loading In An .swf Containing The Loader.
Sorry for the complicated topic. I got a .swf that loads in other .swfs. Rather than figuring out how to make a loader for loading .swfs I thought I'd just use a simple loader in the .swf I'm loading.

However, it doesn't work. It starts fully loaded but doesn't finish. Heres the AS:
ActionScript Code:
_root.stop();PercentLoaded = _root.getBytesLoaded()/_root.getBytesTotal()*100;if (PercentLoaded != 100) {    bar._xscale = PercentLoaded;} else {    _root.play();}


Anyone got a clue? Or would anyone be willing to point me in the direction for a very simple .swf loader.

thanks!

Loader Page - Web Site Starts Behind The Loader
Hey Everyone...

i ran into a very odd problem... to loader page on this site:

http://www.onefortheditch.com/new/loader.html

works fine, except the fact that it doesnt stop the web site from playing while its loading. the web site plays the splash page in the background while its loading...

Any ideas what would be causing this? I use this same feature on my personal site, and it works fine, so i compared codes, and i cant see anything wrong.

Heres the native files if anyone wanted to check it out:

http://www.onefortheditch.com/loader.zip

Thanxs in advnace!! :)

Random Flv Loader + Radom Swf Loader
so i am making a flv player with an flv ad at the beginning, the main flv in the middle, and a swf ad at the end. the issue i have is that the flv ad at the beginning has to be randomly selected from a short list of flv ads in a network folder and the swf ad at the end is a click-able flash animation that has to correspond with the flv ad at the beginning.

so for example:
i have a video flv and swf ad pair for a window company, a restaurant, and a shoe store. when someone loads the video player, the shoe store flv ad is randomly loaded, the main video plays, and at the end, the click-able swf shoe store ad loads.

does that make sense?

THANKS!

Loader Insid Other Loader,how Loadmovie?
Hello

on the stage i have a loader* that shows a movie,in this movie there is a loader# too. in second loader# there is a button that by clicking it, the movie shown in first loader* must be changed.

please tell me how can i doing this with actionscript.........

cheers

Loader.unload() Not Available When Loader Is Not On Displaylist?
HI

I have a preloader swf file that loads in different swf-s using the same Loader instance.
However before loading in the next swf, I'm trying to call Loader.unload()
But it fails since the Loader object is not on the displaylist...
What happens to the data that is loaded with Loader? Is it replaced when Loader.load() is called next time?


ActionScript Code:
public function contentloaded(event:Event):void{
            TweenLite.to(loading_mc, .5, {alpha:0})
            cont = event.target.content
            addChild(cont)
        }
        public function loadnew():void{
            loader.unload()  // Error #2025: The supplied DisplayObject must be a child of the caller.
            if(cont){
                removeChild(cont)
                cont = null
            }
            showloader()
            loader.load(new URLRequest(file))
        }

Loader Or Loader Context Problem
I have two swf files, each one almost with the same classes, the most important one is a Singleton class, each swf does "singleton.getInstance()" . The diference is that one swf is like a container and the other one is like a module.

So when the container loads the module from an absolute path like loader.load("file://c:/modules/module.swf") or loader.load("

Using Stage Properties When Loader From A Loader
im doing a preloader that creates a var of the type loader and then loads another swf and add it to the stage with addChild, the problem is that the loaded swf cannot access stage properties and if i try to use them i get a #1009 runtime error, heres the code

----------PRELOADER-----------
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLET E, done);
l.load(new URLRequest("test.swf"));
function done(e:Event)
{
addChild(l);
}
--------------------------------

and heres the test swf that is very simple
--------- test.swf -------------
var N:Number = stage.stageWidth;
trace(N);
--------------------------------


Hope someone can help this is killing me x.x

URL Loader & Loader LIMIT?
I'm trying to create photo gallerys and have run into a problem.
I have about 30 thumbnails that i wanted to load but the loader only loads 18 and the rest give me URL not found errors?

SO my question is does anybody know if there are size limits for the loaders??

Thanks

[loader] Load Jpg With Loader?
Hi, I making my website and trying to load jpg into a movieCLip which will holds all of my loaded jpg images.

I have a MovieClip called "holder"

and I want to load img into this clip. so I wrote

ActionScript Code:
holder.loadMovie("myPic.jpg");


this part I had no problem, but the thing is that How do I apply a preloader to this? I mean if this image is IN the movie, then I can have a preloader in the first frame and load this pic, but the thing is that I'm now loading this images directly from folder, how do I have a preloader for this?...

I tried this

Frame 1 preloader
Frame 2 load Image code...

just...you know what I mean?...when you load a image directly from folder, can you apply a preloader for that?...I stood up so late only because of this question..makes me so awake...HELP!!! I wanna sleep...

Function In A Function In A Function, A Scope Problem
Is this basic or what.. I have a nested functions, and I'm having a hell of a time getting all my variable through.

ActionScript Code:
var canyouseemee;
public function move()
   {
      for(var i:Number = 0; i < blah; i++)
      {
         zing, and then zang
         if (zing==0)
         {
             guts
         }
         if (zang ==0)
         {
             something else
         }
      }
   }

Now, I had always thought that since var canyouseemee is declared at the topmost layer, that I'd be able to see it from anywhere below it. Well, it turns out that I can only see it from within the move()function, and not anything below it. is this normal? I thought you couldn't see a local variable of a lower (deeper) function, but could see higher (shallower) variables...

Call A Function In A Duplicated Movie Clip Form Another Function : (
i have a movie clip on my root name "pl".
on command, it duplicates with instance name as "y0","y1", etc.

here is the method :

function callPL(transmit,receive,addy,level) {

var newName = "y"+_root.x;
duplicateMovieClip("_root.pl",newName,101);
_root[newName]._x = 400;
_root[newName]._y = 400;

_root.[newName].start(transmit,receive,addy,level); //look here
}


there i attempt to call a function of the newly duplicated clip call "start()".
Start() function is written on the first frame of the movieclip like this :


function start(a,b,address,level) {
a.sendAndLoad(address,b,"Post");

this.path = b;

b.onLoad=function(success) {
gotoAndPlay("start");
}
}


however it seems like the function callPL() could not invoke function start() of the new movieClip.I have no idea how is it so.
Even when i trigger it with a onLoad handler it still doesnt work
pls shed some light.

Calling Constructor In Condition: A Function Call On A Non-function Was Attempted.
Hi guys,

Please help me somebody with this cos I have really no idea. I have made a simply condition calling a constructor of a class. Today I had to add an "else if", what caused the compilator to show me "A function call on a non-function was attempted."...

ActionScript Code:
function loadIt() {    if (var1 == "1") {        var a:SomeClass = new SomeClass(true);    } else if(var2 == "1"){         var a:SomeClass = new SomeClass(false); //<- if this is not here, everything works fine    } else {        var b:SomeOtherClass = new SomeOtherClass();        b.init();    }}

Any ideas? Thanks for any help!

Poco

Filling Function Arguments With Array Items, Function.call()
HI!

I have this code but I cannot work out how to fill in function parameters based on an array and it's length, see line 7

ActionScript Code:
import com.robertpenner.easing.Cubic;MovieClip.prototype.framesTimeout = function(func:Function, frames:Number, args:Array) {    var t:Number = 0;    var mc:MovieClip = this.createEmptyMovieClip(String(new Date().getTime()), this.getNextHighestDepth());    mc.onEnterFrame = function() {        if (t == frames) {            func.call(this._parent,args);            delete this.onEnterFrame;            this.removeMovieClip();        } else {            t++;        }    };};MovieClip.prototype.movex = function(x:Number, frames:Number) {    trace(x+" "+frames)    delete this.movex.onEnterFrame;    this.movex.removeMovieClip();    if (!frames) {        frames = 20;    }    var t:Number = 0;    var sx:Number = this._x;    var ax:Number = x-this._x;    var mc:MovieClip = this.createEmptyMovieClip("movex", this.getNextHighestDepth());    mc.onEnterFrame = function() {        if (t == frames) {            delete this.onEnterFrame;            this.removeMovieClip();        } else {            t++;            this._parent._x = Cubic.easeOut(t, sx, ax, frames);        }    };};MovieClip.prototype.otherfunction = function(param1, param2, param3, param4){    trace(param1+" "+param2+" "+param3+" "+param4)}mc.framesTimeout(movex, 50, [100, 50]) mc.framesTimeout(otherfunction, 200, ["asd", 1, 2, 55])

Is it possible to call a function and fill in the parameters based on an array and it's lenth?

My Function Isn't Functioning/Actionscript To Call A Function Flash MX 2004
Hello,

Well in theory I know how to create a function but for some reason I am unable to call it.

Can someone take a look at it and tell me what went wrong. Basically when I go to "a certain page" I want to click on a button and have it go to another page known as "pics" it then will load a jpeg there known as jpeg loader. Now I know it works properly without a functin, but because I am lazy I do not want to write more code than I have to, there are like 300 differnt jpegs I have to load. Thus I need to create a function.

here is my AS


ActionScript Code:
//this is on frame one of my root timeline
//I am trying to call the function "display" on release of my button
 
omnihotelButton.onRelease = display ("J010 Omni Hotel.jpg");
 
 
//this is my function that I set up it is also on my root, but on a different frame
//this function is named display and it goes to the "pics" page and stops
where it then loads a jpeg which is et up as my variable.
//the xscale and the yscale are just setting up my size of the jpeg.
 
function display(jpeg){
    _root.gotoAndStop("pics");
    jpegLoad_mc.loadMovie(jpeg);
    jpegLoad_mc._xscale=90;
    jpegLoad_mc._yscale=90;
}

Loader.content.width Or Loader.width?
whats the difference, if there is any?
between:
loader.content.width and loader.width?

Function Calling From The _root But Call A Function Within A Instance
I have created a new instance 'Check_1' to work as a checkbox with a set of propertys and functions.

All ive done is created the functions in a script in the first frame of the instance-movie these are...

Simple......
================================================== =======

selected = -1;
function select_frame (FrameNum) {
gotoAndPlay (FrameNum);
}
function change_select () {
select_frame(2);
trace (selected);
}
function change_unselect () {
select_frame(1);
selected = -1;
}

================================================== =======

now from the _root i wish to call the above functions to change the instance propertys, it all works fine from within the instance but i also need to use the functions for that instance from the _root...

iv'e tried the follow with no joy...


_level0.Check_1.change_select()


Any light would be greatly appreciated.

Parsing Data To A Function And Altering It Inside The Function
Hi all

I need to parse variables to a function and let the values of the variables be changed inside the function. But in a way that the data are actually changed, not only a reference to the data! It is not possible using primitive data but should be possible with composite data.
But I cant get it right - any suggestions?

code:
test = new Object();
test = false;

aFunction = function(control){
control = true;
trace(test);
other code here...
}


How can I make the trace(test) output true when I call the aFunction(test) with test as parameter?

Hope anyone have the answer!

Ciao ciao

T

Define The OnMouseDown Function To Point To A Member Function
Hi,

I have a class called CField that contains a MovieClip. And I like to be able to call a member function inside my class, when the mouse click on the MovieClip. If I use the callback function onMouseDown = function() from inside the class, the function is overwritten by the last created instance of the class (see the the Main Program). How do I define the onMouseDown function to point to a member function?


// Main Program
.
// Create and draw 10 fields
for (i=0;i<10;i++)
{
var field:CField = new CField(i*50, 50);
field.Draw(i);
}
.

My class is looking more or less like this:

// Field Class
class CField
{
// Properties
var m_nPosX:Number;
var m_nPosY:Number;
var m_mcField;

// Constructor
function CField(nPosX:Number, nPosY:Number)
{
this.m_nPosX = nPosX;
this.m_nPosY = nPosY;
}

public function Draw(nCount:Number)
{
var sInstance:String = new String(nCount.toString(10));
this.m_mcField = _root.createEmptyMovieClip (sInstance, nCount);
with (this.m_mcField)
{
_x = this.m_nPosX;
_y = this.m_nPosY;
loadMovie("Field.swf", nCount);

onMouseDown = function ()
{
trace("Mouse Clicked");
}
}
}
}

Inside XmlOnload Function Can Not Call Other Function Directly
I have a question, why the test function can not be called ?
Thanks.

Code:
class testClass {
public function testClass() {
var XMLData:XML = new XML();
XMLData.load("coonfig.xml");
XMLData.onLoad = this.xmlOnLoad;
}
public function xmlOnLoad(success:Boolean) {
if (success) {
// this.test();
test();
}
}
public function test () {
trace("test success");
}
}

Actionscript Function Similar To PHPs Explode Function?
Hello everyone, first off, I'd like to say hi to everyone as this is my first post and I have joined very recently! So yeah, I'm glad to be here and yeah, hope I find what I need.

Right, well for those of you who know PHP there is a function known as explode(), which basically splits a string apart by a certain character and throws it into an array.

For example, in PHP.


PHP Code:



$string = "lol,text,omfg,wow,hi";




I can explode that string by the , character and it would split up everything and throw each little "section" into an array.


PHP Code:



$bits = explode( ',', $string );




I can now access access the bits by $bits[0], $bits[1], $bits[2], $bits[3], and $bits[4].

Now, is there anyway you can do this in Actionscript? Say I have a string in actionscript and I've datatyped it to a string.


PHP Code:



var myString:String = "text1|text2|text3|text4";




How can I explode, or break apart, the string by the | character and get the "text1", "text2", etc, strings?

Mysql->PHP->FLASH Function. (Passing Function To A Package)
I've just started with ActionScript3.0, and is currently working on a flash that is to communicate with a mysql database and have found a great deal of example code online that I've started to work with.
Currently I have the following package added to my project:


Code:
package
{
import flash.events.*;
import flash.net.*;

public class SendAndLoad
{
public function SendAndLoad()
{}
public function sendData( url:String, _vars:URLVariables, completeFunc:Function ):void
{
var request:URLRequest = new URLRequest( url );
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
request.data = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener( Event.COMPLETE, completeFunc );
loader.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
loader.load(request);
}
//private function handleComplete( event:Event ):void
//{
// var loader:URLLoader = URLLoader( event.target );
// trace( "Par: " + loader.data.par );
// trace( "Message: " + loader.data.msg );
//}

private function onIOError(event:IOErrorEvent):void
{
trace("Error loading URL.");
}
}
}



And is running the following code in my flash:


Code:
import SendAndLoad;
import flash.net.URLVariables;

function loadUsername( event:Event ):void
{
var loader:URLLoader = URLLoader( event.target );

//userNameText.text = "ffff";
userNameText.text = loader.data.user;
}

var url:String = "pages/test.php";
var vars:URLVariables = new URLVariables();
var sal:SendAndLoad = new SendAndLoad();

sal.sendData( url, vars, loadUsername );



As you can see I am trying to seperate the function to be called when the return value of the page I am accessing returns with a value, so I wont need to pass all different actions to be called on different pages I will be requesting throughout my flash program.
But as it is now, the function loadUsername, never even gets called, which I assume is because the package can't call the function outside it.

As I said, I am just starting out with ActionScript 3.0, and is kind of stuck at this.
Any thoughts?

Mysql->PHP->FLASH Function. (Passing Function To A Package)
I've just started with ActionScript3.0, and is currently working on a flash that is to communicate with a mysql database and have found a great deal of example code online that I've started to work with.
Currently I have the following package added to my project:

Code:
package
{
import flash.events.*;
import flash.net.*;

public class SendAndLoad
{
public function SendAndLoad()
{}
public function sendData( url:String, _vars:URLVariables, completeFunc:Function ):void
{
var request:URLRequest = new URLRequest( url );
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
request.data = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener( Event.COMPLETE, completeFunc );
loader.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
loader.load(request);
}
//private function handleComplete( event:Event ):void
//{
// var loader:URLLoader = URLLoader( event.target );
// trace( "Par: " + loader.data.par );
// trace( "Message: " + loader.data.msg );
//}

private function onIOError(event:IOErrorEvent):void
{
trace("Error loading URL.");
}
}
}


And is running the following code in my flash:

Code:
import SendAndLoad;
import flash.net.URLVariables;

function loadUsername( event:Event ):void
{
var loader:URLLoader = URLLoader( event.target );

//userNameText.text = "ffff";
userNameText.text = loader.data.user;
}

var url:String = "pages/test.php";
var vars:URLVariables = new URLVariables();
var sal:SendAndLoad = new SendAndLoad();

sal.sendData( url, vars, loadUsername );


As you can see I am trying to seperate the function to be called when the return value of the page I am accessing returns with a value, so I wont need to pass all different actions to be called on different pages I will be requesting throughout my flash program.
But as it is now, the function loadUsername, never even gets called, which I assume is because the package can't call the function outside it.

As I said, I am just starting out with ActionScript 3.0, and is kind of stuck at this.
Any thoughts?

Functions Inside A Function Returning To Previous Function
This is a kind of long post so for your benifit here's some story Tags, if you don't want to read my sobbing story, then just look for the /story tag
<story>
Hello there, I'm trying to build a semi-combat system for a small RPG that I am making. I'm to the part where I am trying to make a combat system based upon AD&D 2nd Edition Rules, that's Dungeons and Dragons. It involves rolling for initiative, rolling Thaco(Deciding whether or not you hit), and then deciding on how much damage is inflicted.

So as I was trying to automate the task of choosing who goes first(Initiative), the long process of writing the code came about and I realized that I will have to write the same code twice. Once for the monster going first and again for the character going first.
</story>
What I want to do is to write a function that goes into another function if the parameters are met and then that function will test some more variables and if the variables don't agree, the function will resume from whence it broke off into the new function.

ActionScript Code:
function attackAction(){
    //Roll d10 for each party
    cr=Math.round(Math.random()*9)+1;
    this.cr_txt.text=cr;
    er=Math.round(Math.random()*9)+1;
    this.er_txt.text=er;
    //If the enemies roll is greater, then have him attack first
    if(er>=cr){
That's where a new function would come in. It would be something like

ActionScript Code:
function monsterTurn(){
    //Test Thaco
    if(Math.round(Math.random()*19)+1>=_root.monsterThaco){
    //Roll for damage amount
        damage=Math.round(Math.random()*_root.monsterAttack);
        //Display message of Damage and takes damage from you
        this.actions_txt.text="The Monster hits you for "+damage;
        this.Health-=damage
        //sees if the character is dead
        if(this.Health<=0){
        this.actions_txt.text="Oh no!  You died";
        }
        else{
        //Go back to the previous function and resume from there
Then of course there would be a playerTurn() that would do everything similar except test the player's variables.
<story>
If you're going to say that I should just have it list the commands, I tried that. It was far too long and complex to keep track of even with notes.
</story>

So can anyone help me out with Going through a function, hitting an if statement, going to a function based upon the statement, then testing a statement inside of the second function, then returning to the first function if the statement is false and doing the other part of the if statement in the first function.

It's difficult for me to explain this, but I hope you go the general jist. Thanks in advance.

Mysql->PHP->FLASH Function. (Passing Function To A Package)
I've just started with ActionScript3.0, and is currently working on a flash that is to communicate with a mysql database and have found a great deal of example code online that I've started to work with.
Currently I have the following package added to my project:
quote:package
{
import flash.events.*;
import flash.net.*;

public class SendAndLoad
{
public function SendAndLoad()
{}
public function sendData( url:String, _vars:URLVariables, completeFunc:Function ):void
{
var request:URLRequest = new URLRequest( url );
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
request.data = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener( Event.COMPLETE, completeFunc );
loader.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
loader.load(request);
}
//private function handleComplete( event:Event ):void
//{
//var loader:URLLoader = URLLoader( event.target );
//trace( "Par: " + loader.data.par );
//trace( "Message: " + loader.data.msg );
//}

private function onIOError(event:IOErrorEvent):void
{
trace("Error loading URL.");
}
}
}

And is running the following code in my flash:
quote:import SendAndLoad;
import flash.net.URLVariables;

function loadUsername( event:Event ):void
{
var loader:URLLoader = URLLoader( event.target );

//userNameText.text = "ffff";
userNameText.text = loader.data.user;
}

var url:String = "pages/test.php";
var vars:URLVariables = new URLVariables();
var sal:SendAndLoad = new SendAndLoad();

sal.sendData( url, vars, loadUsername );


As you can see I am trying to seperate the function to be called when the return value of the page I am accessing returns with a value, so I wont need to pass all different actions to be called on different pages I will be requesting throughout my flash program.
But as it is now, the function loadUsername, never even gets called, which I assume is because the package can't call the function outside it.

As I said, I am just starting out with ActionScript 3.0, and is kind of stuck at this.
Any thoughts?





























Edited: 10/09/2008 at 08:46:50 AM by _TT_

Function That Wait's 5 Seconds And Runs Anothr Function
hy...I want to make a function that waits 5 seconds, after that to run another function that changes the content (changeContent) to the next label

this is all i managed to do...I hope it's wright

function autorun() {
if (button_label = 0) {
changeContent(1);
} else if (button_label = 1) {
changeContent(2);
} else if (button_label = 2 ) {
changeContent(3);
} else if (button_label = 3) {
changeContent(4);
} else if (button_label = 4) {
changeContent(5);
} else if (button_label = 5) {
changeContent(0);
}
}

I need this in AS2.0....
Can someone help me? Thanks!

[F8] [AS2] Access An Instance Variable From Within A Function Within Another Function
So here is the scenario that has completely stumped me. I have a class, within the class a function and within that function an xml onload handler. So herein lies the problem, I need to store the array of values that I receive from the XML into an instance variable belonging to the class. How can this be achieved?

To illustrate:

Class A {private var values:Array;public function getValues():Void{Xml sendandload code here.xmlReply.onLoad = function(){iterate through xml code and generate array of values.Store this array back into values belonging to class A}}}

using the variable straight up doesn't work.
if I use "this" it refers to the onload function, not the class.
i tried creating another class method called setValue and calling this.setValue(arr) and setValue(arr), but neither of those work.
i even tried combinations of _parent and this, still no go.

The only way I can get it to work is to make reference to _root.class.value, but this is not solid code and is very impracticale, especially if what calls the class doesn't happen to be in the root of the file.

Any ideas would be appreciated.

How Can You Make Sure One Function Completes Before Second Function Runs?
Hi guys:

I apologize if it's a really obvious answer, but I can't even think of the right terms to search on right now!

I have two functions. One is an xml connector trigger, that calls a PHP program to get xml data that includes content and formatting information. It will read the formatting information into hidden text fields.

The second function reads the hidden text fields, and applies the data from them to the style for the content fields:

Here's the prototype (pooh just being a "foo" name), contained in the root of the application:

Code:
// Initial poll for the XML data (this also runs the PHP that updates the movie)
var f_xml_trigger:Function = function(){
xml_community_board_connector.trigger();
}
_global.f_xml_trigger = f_xml_trigger;

// Function to apply styles:
var f_format:Function = function(){
Dashboard_Message_TextArea.setStyle("backgroundColor",Pooh.text);
}
_global.f_format = f_format;

_global.f_xml_trigger();
_global.f_format();
What's happening is _global.f_format is running before _global.f_xml_trigger has completed populating the fields.

I made these Global so a movie clip that's running a clock can periodically check for and apply updated content & formatting.


Code:
function getTime() {
var time = new Date();
<snip>
var second = time.getSeconds();
<snip>

if (second == 30 && _global.t30flag == 1)
{
// The _global.t30flag is used to make sure this only runs once
// otherwise it would run at the frame per second rate (i.e. 12fps = 12 times
// during the 30th second

_global.f_xml_trigger();
_global.t30flag++;
}

if (second == 31 && _global.t30flag == 2)
{
// Apply the formatting brought down by the xml trigger.
// Can't be done at the same time, because it runs before the values are updated.
_global.f_format();
_global.t30flag++;
}

<snip>
But rather than depending on frame numbers or seconds (especially since a 1 second delay between when text changes and formatting changes is annoying to say the least!)...I would think there must be a way that as soon as we can get a success returned from _global.f_xml_trigger we can run _global.f_format.

Any suggestions?

Thanks,
Matt

Using Variables Created Inside A Function Outside The Function?
I am trying to use a variable I am creating inside of a function, outside of that function, but I seem to have a scope issue when I do this.

My code is:

Code:
function drawlines(centerx, centery, radius, radians){
var radiansSoFar:Number = 0

var piechart:MovieClip = new MovieClip();
piechart.name = "piechart"
piechart.x = stage.stageWidth/2;
piechart.y = stage.stageWidth/2;


stage.addChild(piechart);
}
but I want to make a function outside of this which removes the variable piechart, but because im so unfamiliar with how flash names instances now I have no idea how to do this.

It works if I define var piechart:MovieClip = new MovieClip() outside of the function, but this isnt very useful as I eventually need to create multiple movieclips dynamically and name them dynamically.

So basically how would make it so I would be able to use the code


Code:
function removeChart(chartname){
stage.removeChild(chartname)
}
to dynamically remove a movieclip I created in a function?

Cannot Call Button Function Within Another Event Function
Hopefully someone can help me out with this one. I'm importing XML in order to draw images into an animated scrollbar, and would like to nest a button function within the function urlLoaded as listed below:

import caurina.transitions.*;

var urlCall:URLRequest = new URLRequest("pics/hotel_dreams/hotel_dreams.xml");
var urlLoader:URLLoader = new URLLoader();
var xml:XML;
var xmlList:XMLList;
urlLoader.load(urlCall);
urlLoader.addEventListener(Event.COMPLETE,urlLoade d);

var arrayThumb:Array = new Array();
var photoContainer:Sprite = new Sprite();
addChild(photoContainer);
photoContainer.mask=thumb_holder;


function urlLoaded(event:Event):void {


xml = XML(event.target.data);
xmlList = xml.children();
trace(xmlList.length())
for (var i:int=0; i<xmlList.length(); i++) {
var thumb:Thumbnail = new Thumbnail(xmlList[i].url);
arrayThumb.push(thumb);
arrayThumb[i].y = 67.5;
arrayThumb[i].x = xml.children().x_position[i];
photoContainer.addChild(thumb);
arrayThumb[i].gallery = xml.children().gallery[i];

trace(arrayThumb[i].gallery);


}


}

my hope is to create a button that looks something similar to the following in order to execute an if then statement within the function controlling the visibility of images from the XML based on their gallery property value.

btn_gallery_2.addEventListener(MouseEvent.CLICK, open_gallery_2);
function open_gallery_2(event:MouseEvent) {

if (arrayThumb[i].gallery == 2) {
arrayThumb[i].visible = true
}

}

I have been trying to nest within the urlLoaded function to no avail. By running trace statements I can see that [i] is inaccessible when nested within another function within urlLoaded and when completely outside of the urlLoaded function.

The Thumbnail class referenced is in an .as file that looks like this:

package {
import flash.display.Sprite;
import flash.display.Loader;
import flash.net.URLRequest;

public class Thumbnail extends Sprite {

private var url:String;
private var loader:Loader;
private var urlRequest:URLRequest;
public var gallery:Number

function Thumbnail(source:String):void {
gallery = 0
url=source;
drawLoader();

}

{
private function drawLoader():void {

urlRequest=new URLRequest(url);
loader=new Loader ;
loader.mouseEnabled=false;
loader.load(urlRequest);
loader.x=-0;
loader.y=-68
;
addChild(loader);

}}}}

I have the suspicion that I am missing something very basic. If anyone out there might be able to give me some insight, then I would be appreciative.

thanks very much

Is There A Limit To How Many Function Calls Are Made In A Function?
Hi,

I have a question on what is the limitation of the number of functions that can be called in Actionscript in a single "function." I use Flex to run all of my Actionscript listed beow.

Is there a certain number of if statements nesting only allowed in a single private function? I have a function call as in the following, and I wanted to add some other Alert statements to show users if there is an error in the process, but it appears that the file writing process is so long that I never see the Alert.show pop up.

Could anyone here please tell me what I might have done wrong here, since I could not get any Alert.show statements show up after scenario_save(1) or in scenario_save() function itself.

Question, if there is a limit to how many functions I can insert due to "time issues," is there a way I can get around it?

Thanks for your help.

Main Event Handler:

private function clickHandler3(event:ItemClickEvent):void {
if (String(event.index) == '0') {
currentState="";
}
if (String(event.index) == '1') {
scenario_find.send();
currentState="Scenario Show";
}
if (String(event.index) == '2') {
scenario_save(0); //The user would only save the scenario
}
if (String(event.index) == '3') {
//The user would save and run the scenario
scenario_name.send();
filename1.text= scenario_name.lastResult.scenarios.filename;
scenario_save(1); //Save record and output the file to filename1.text
//Execute the exe file and input entries back to the database
}
}

Child Function of Scenario Save:
private function scenario_save(x:int):void{

var pop:int= scenario_load.lastResult.scenarios.number_entries;
var pop2:int=scenario_load.lastResult.scenarios.number _entries-1;
number1.text= pop.toString();
if (pop2 == 0) { //if there is only one item, no index produced
i1.text= i.toString();
population1.text=scenario_load.lastResult.scenario s.scenario.population;
region_id1.text=scenario_load.lastResult.scenarios .scenario.region_id;
query1.text= "UPDATE My_Scenario SET Population='" + population1.text + "' WHERE Region_id='" + region_id1.text + "' AND ID='" + id1.text + "'";
hello1.text=region_id1.text + " " + population1.text;
update_record.send();
if (x==0) {
//Don't do anything, since there is nothing to run
} else if (x==1) {
execute_scenario.send();
}
}
else {
for (var i:int=0;i<=pop;i++) { //if there are more than one item, indices would be produced
i1.text= i.toString();
population1.text=scenario_load.lastResult.scenario s.scenario.population;
region_id1.text=scenario_load.lastResult.scenarios .scenario.region_id;
query1.text= "UPDATE My_Scenario SET Population='" + population1.text + "' WHERE Region_id='" + region_id1.text + "' AND ID='" + id1.text + "'";
hello1.text=region_id1.text + " " + population1.text;
update_record.send();
if (x==0) {
//Don't do anything, since there is nothing to run
} else if (x==1) {
execute_scenario.send();
//I want to add some other alert statements here, but they are not working
}
}
}
}

OOP In Flash: Calling A Function W/in A Function Class?
Okay so I am reading through sens tutorial on OOP and updating my game that I am making. It is much easier to code this way (IMO) but still hitting snags.
I am trying to get through this code:

ActionScript Code:
House = function(){        this.floors = 4;         this.siding = "Red";         this.outputSiding = function(){            trace(this.siding);         };     };         // create an instance of the House class     myHouse = new House();     myHouse.outputSiding(); // traces "Red"  

Now as it seems to me, I have nearly the same thing (I will condense this to save space):

ActionScript Code:
//set new character function()character = function (depth, x, y, charType, name, HP, MP) {    //sets stats used; this works fine :)        //attachMovie and set x/y     _root.attachMovie(this.name+"_mc", this.name+"MC", this.depth, {_x:this.x,_y:this.y});    /*this is where I am having trouble; it won't do anything!I have tried tracing to no availalso, can I set the x and y coords somehow with thealready made object x and y? I am tired right now andcan't think of a way but what I have done, which doesnothing as this function won't go!*/    statsBox = function(depth)  {        this.depth = depth;        trace(this.depth+newline+'hello');        this.x = enemy._x+130;        this.y = enemy._y-50;        _root.attachMovie("stats_mc", statsNameMC, this.depth, {_x:this.x,_y:this.y});    };};enemy = new character(30, 350, 200, 'enemy', 'genericName', _root.EHP, _root.EMP);enemy.statsBox(50);

that's it, pretty much. So what's wrong? Maybe I'm too tired for this right now...
thanks.

Cant Remove Event Listener (function In A Function)
I have this function, that when given a movie clip and a destination, it moves it to there, and eases out.

I have buttons that control where it moves to. This all works great.
But I want it so that if it is moving, and a new destination is clicked, it stops and moves to the new destination.

When I remove the event listener, nothing happens. But the event listener removes properly when it stops. (just wont when it is moving)

So the tricky part is this. I have a function in a function, It is there so the moving event:enter_frame parrt can see the same variables passed to it from the click.

If I move this function out of the other function, I can remove it. But it can not access the variables and does not move.

Part that does not work
if (isMoving == true) {// are we moving?
trace('is moving:'+isMoving);
removeEventListener(Event.ENTER_FRAME, mover);// stop moving

PHP Code:



function easeTo(toMove:MovieClip, dest:Number):void {

    trace(toMove +' is being moved to: '+ dest);

    if ( toMove.x  != dest ) {//are we already there? If so, do nothing
        if (isMoving == true) {// are we moving?
            trace('is moving:'+isMoving);
            removeEventListener(Event.ENTER_FRAME, mover);// stop moving
        } else {// not moving, set dest and go.
            trace('is moving:'+isMoving);// reads faluse
            isMoving = true;// now set to true

            addEventListener(Event.ENTER_FRAME, mover);// start moving
        }
    } else {
        trace('we are already there');// do nothing
    }

    function mover(event:Event) {// move. Function here because it needs to access internal varibles
        
        if (Math.abs(dest - toMove.x) < 1) { // are we there? yes? stop event listener
            removeEventListener(Event.ENTER_FRAME, mover);
            isMoving = false;
            wDirection = '';
        } else {
            toMove.x += (dest - toMove.x) * speed;
        }

    }


OOP In Flash: Calling A Function W/in A Function Class?
Okay so I am reading through sens tutorial on OOP and updating my game that I am making. It is much easier to code this way (IMO) but still hitting snags.
I am trying to get through this code:

ActionScript Code:
House = function(){        this.floors = 4;         this.siding = "Red";         this.outputSiding = function(){            trace(this.siding);         };     };         // create an instance of the House class     myHouse = new House();     myHouse.outputSiding(); // traces "Red"  

Now as it seems to me, I have nearly the same thing (I will condense this to save space):

ActionScript Code:
//set new character function()character = function (depth, x, y, charType, name, HP, MP) {    //sets stats used; this works fine :)        //attachMovie and set x/y     _root.attachMovie(this.name+"_mc", this.name+"MC", this.depth, {_x:this.x,_y:this.y});    /*this is where I am having trouble; it won't do anything!I have tried tracing to no availalso, can I set the x and y coords somehow with thealready made object x and y? I am tired right now andcan't think of a way but what I have done, which doesnothing as this function won't go!*/    statsBox = function(depth)  {        this.depth = depth;        trace(this.depth+newline+'hello');        this.x = enemy._x+130;        this.y = enemy._y-50;        _root.attachMovie("stats_mc", statsNameMC, this.depth, {_x:this.x,_y:this.y});    };};enemy = new character(30, 350, 200, 'enemy', 'genericName', _root.EHP, _root.EMP);enemy.statsBox(50);

that's it, pretty much. So what's wrong? Maybe I'm too tired for this right now...
thanks.

Pausemovie Function Inside Fadein Function
Last edited by pusherman : 2007-06-21 at 10:26.
























I am trying to merge two functions together. The result is however, pausemovie function does not work (perhaps overriden by onEnterFrame) and mypic's alpha reaches 100 by increments of 7.


ActionScript Code:
//MC:mypic1 appears.
createEmptyMovieClip("fadein", 222);
fadein.onEnterFrame = function() {
    pauseMovie(4);
    if (mypic1._alpha<100) {
        mypic1._alpha += 7;
    } else {
        removeMovieClip("fadein");
    }
};


My pausemovie function is on my 1st frame and is as follows:



ActionScript Code:
function pauseMovie(seconds) {
        stop();
        var startTime = getTimer();
        var endTime = seconds * 1000;
        this.onEnterFrame = function(){
                currentTime = getTimer();
                if(currentTime - startTime > endTime){
                        //this is where your action goes
                        play();
                        delete this.onEnterFrame
                };
        };
};


I would appreciate any help.
Thank you.

Target A Function In A Function In A Object :)
Uggg, how do I target a function that is in a function that is in an Object...

I am building a componet and when the componet runs though the script and finishes I want to call a genral function that will be replaced with a spacific function that I set in the Componets Properties window.

So my Object function X2 looks something like this...

ScalerClass.prototype.clipEndAction = function(loadHandler) {
loadHandler();
};
ScalerClass.prototype.myOtherFunction = function(){
trace("This function is a function")
}
//now if I target it like this within the object it works fine.
loadHandler=myOtherFunction
this.executeCallBack(loadHandler);

But How do I set up so that if this is in an componet i could target it from the Componets Pro Win.

Passing A Function Ref To A Function With Parameters
Can anyone tell me how to pass a function reference to a function WITH parameters?

I want to do something like this:

genericFunc = function(funcRef, params){
//do something that takes a while
//and when done...

//call my funcRef with params:
funcRef(params)
}
func1 = function(){
//trace("here's funct#1");
}
func2 = function(arg1, arg2){
//trace("here's func#2 with arguments "+arg1+" and "+arg2);
}

Test 1: genericFunc(func1);
Test 2: genericFunc(func2, ...) //this is where I lose it.

So, this works fine if I'm passing in a function call that requires no parameters (test 1). But what I really need to do is keep this flexible so that I can reference different functions with varying numbers of parameters (test 2).

Copyright © 2005-08 www.BigResource.com, All rights reserved