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




Passing Arrays Between Classes



how do I create an Object Array in one class and pass it to another class?if I can't do this, what's the workaround?



KirupaForum > Flash > ActionScript 3.0
Posted on: 12-18-2007, 03:14 PM


View Complete Forum Thread with Replies

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

Passing Arrays Between Classes
how do I create an Object Array in one class and pass it to another class?
if I can't do this, what's the workaround?

Passing Arrays Between Classes;
Hi there,

If I have a multidimensional Array "myArray" in an instance of class A containing a variety of datatypes,
what is the best way of getting this data to an instance of class B? I need the data to be in the same structure, but without maintaining a reference to the original "myArray"?

Is there a way of taking a snapshot of an array in it's current state and then creating a totally new array from it?

I guess what I'm asking is can you clone an array?

Thanks

Passing Arrays Between Classes
how do I create an Object Array in one class and pass it to another class?
if I can't do this, what's the workaround?

Arrays And Classes
hi all, this is quite complicated so i will try and explain the best i can, hopefully someone can help as this is annoying me now

ok so i have a flash file with 2 frames, thats it, the first frame has this code


Code:
lang = new Array();
lang = ["1,2,3,4,5"];
it creates an array with 1,2,3,4,5, then on the second frame i have


Code:
stop();
var lRoot:MovieClip = this;
var mainText:Array = lang;
var worldSetup = new worldSetup(lRoot,mainText);
this creates lRoot movieclip and puts the array in to mainText array and also creates an instance of worldSetup. so far so good, now my issue is in my class worldSetup i want to access a single element from the array, the code below works fine and traces the whole array, but once i try and look for a single element it returns undefined?? is it just a general rule of arrays i am breaking? any way the code in the class called worldSetup.as is...



Code:
import mx.utils.Delegate;
class worldSetup {
public var _lRoot:MovieClip = null;
public var mainN:Object = null;
public var _mainText:Array;

public function worldSetup(lRoot:MovieClip, mainText:Array) {
_lRoot = lRoot;
_mainText = mainText;
init();
}

public function init():Void {
//this does not work
trace(_mainText[1])
//this does work
trace(_mainText)
}
}
any ideas would be most appreciative, cheers for all the help so far guys

sam

Searching Arrays For Classes
Hi,

If an array is filled with objects of different classes, what do I use as the search criteria using IndexOf to find if an object of class X is stored inside the array?

Thanks.

Arrays In Custom Classes
The class below is in a document called (Node.as)

class Node {
private var _z = new Array();
public function Node(z) {
this._z[0] = z;
}
function getz(index) {
return this._z[index];
}
}

This is the actionscript of the main document

import Node;
//create line placeholders
var node0:Node = new Node(234);
trace(node0.getz(0));
var node1:Node = new Node(345);
trace(node0.getz(0));
var node2:Node = new Node(786);
trace(node0.getz(0));

Why does the trace yield completely different numbers?????

Help Is It Legal To Create Arrays By Same Name But Within Different Classes?
Is it OK to create new arrays with the same name in different classes or different object instances from the same class?

I assumed that each new array created within a class as a property for the new object from that class would mean that each new object would have its own individual array, but I get wacky results when I refer to or mess with theses arrays outside of its own class methods.

For example, I can create object1 and object2 from a single class and I tell the class to fill each object's array differently.

object1.theTestArr gets filled with 1,1,1,1
object2.theTestArr gets filled with 2,2,2,2

I can do a trace and get results back as the two arrays by the same name are different for each object.

trace( object1.theTestArr ) // result "1,1,1,1"
trace( object2.theTestArr ) // result "2,2,2,2"

Great, It looks like I got different arrays. If I manipulate these arrays within its own class methods later, they work great.

BUT, if I manipulate these arrays with a function outside of the class, the function will see the contents of object1.theTestArr for instance and act like it can change the array, but when I check the results from within the objects own method, IT HASN'T CHANGED!

Am I missing something basic about arrays here?
I'm on a deadline of course, any help much appreciated!

Quick Question Regarding Arrays Of Classes
Hi, I am a C++ programmer but have been asked to complete a small task in Actionscript over the weekend. I am currently having a little difficulty...

I have a classes named baddie that contains all the variables of a baddie spaceship the constructor of which looks like this:


Code:
public function baddie( inIDepth:Number, inX:Number, inY:Number )
{
//create default baddie...
iDepth = inIDepth;
var spriteManager:spriteManagement = new spriteManagement();
baddieShip = spriteManager.makeSprite("mBaddie1", iDepth);
baddieShip._x = inX;
baddieShip._y = inY;
}
All this does is load a bitmap into a movieclip file (assume any variables you see which aren't defined are members of the class) at the specified position.

I'm trying to display a grid of 5*4 of these 'baddies' on the screen and I'm doing it like so:


Code:
case 1 :
{
//Easy pattern, set up only normal baddies...

for( var i:Number = 0; i < MAXNUMBEROFBADDIES; i++ )
{
//Add normal (default) baddies to array only...
if( coloumCount < 5 )
{
curX+=30;
coloumCount++;
}
if( coloumCount >= 5 )
{
curY+=50;
curX = 50;
coloumCount = 0;
}
var currentBaddie:baddie = new baddie( iDepth+10, curX, curY );
baddies.push( currentBaddie );
}
break;
}
Basically in the above code I'm just trying to draw the baddies to the screen in a sort of grid format and at the same time add all the baddies on the screen to the array named baddies.

However, the only baddie that is drawn to the array is the last one in the array.

Any idea why this is?

J

Passing Vars Between Classes
Just got my brain around broadcasting from one class to a listener in another, but how do I send a var with the event dispatch to the listener?

Thanks

Passing Variables Between Classes
Hello,

Looking to figure out how I can pass a variable from my documentClass to another class.

I have the docClass which loads some images, then i'm trying to pass the total width of those images to the scrollBar class that will resize a movie clip based on the number it is passed from the doc class.

The scrollBar class is attached to the movieclip via the library linkage and is not imported to the docClass. I've tried:

(in docClass)

private var scrollB:scrollBar;
scrollB = new scrollBar(someNumber);

(...and then in the scrollBar class)

public function scrollBar(myNum:Number):void
{
trace(myNum);
}

...this does not work. help please!

thanks.

Passing Variables Between Classes
I've just about got my head round broadcasting an event from one class and watching for the event with a listener in a different class, but how do I pass a variable along with the event?

I want to broadcast the number of a whichever button is pressed in my listbox class to whatever is observing it (mp3player class, flvplayer class etc).

Thanks in advance.

Passing Events Across Classes
Hi

Could someone help me with this? Im fairly new to AS3 and especially event handling.

If i have a top level class that instantiates 2 different classes, how can i pass an event from one of the sub classes into the other sub class going through the top level class?

Is this a case when bubbling would be useful?

Thanks

Passing Events Between Classes
Hoping someone can help me. I have been trying to find some clear information regarding passing on events to other classes.

I have multiple instances of class Segment.as. In it I have the following code.


Code:
public function fadeOut4(ev:TweenEvent){
var fadeOut4:Tween = new Tween(this._clip.p3, "alpha", Regular.easeOut, 1, 0, 0.6, true);
fadeOut4.addEventListener(TweenEvent.MOTION_FINISH,dispatchTheEvent);
}
public function dispatchTheEvent(ev:Event){
dispatchEvent(ev);
}
Now, what I am wanting to do is have another class, FrontPage.as, listen for the dispatchEvent(ev), and execute a function when it has received the event. How do I do this????? Nothing I have found out there explains how to pass events between classes. Please help.

Passing Info Between Classes
OK. I have 3 classes: a mainAsDoc, an Iterator class, and a "Make" class.
The make class outputs info based on sensors. I have it functioning and working properly- reads and displays the data just fine. But I can't seem to get the Iterator class to recognize that variable. I thought this would be farily straight-forward, but am finding that it's not.

So: the relevant code (?) looks like this :
Make.as

Code:

public var alfNum:Number;//in body

//later
var msg:OscMessage= event.data;
var msgNum:Number =msg.args[0]; //0 is light meter
alfNum= msgNum * .001 + .17;
Then in the iterator I try to use alfNum but it won't register. No errors-- just doesn't do anything. Iterator and Make are in the same package which is manged by the mainClass doc. I'm probably missing something basic here. Forgive me and thanks in advance.

The iterator.as just needs to read the alfNum and apply it to some objects that it's iterating.

Passing Variables Between Classes
I think I am making this more difficult than it really is. I'd like to pass a variable from one class to another once a file has loaded. Currently, I have a ListLoader class that querys a PHP/mySQL which returns XML. I'd like to create another class that processes that XML but I'm not sure how to pass it only after it's loaded. Is it a matter of getter/setter methods or am I missing something really simple (or something else entirely)?

Below are the two classes I'm struggling with.









Attach Code

class ListLoader {
public var isLoaded:Boolean = false;
public var xml:XML = new XML();
public function ListLoader() {
//trace("ListLoader instantiated");
}
public function getList(url:String,action:String):void {
var urlVars:URLVariables=new URLVariables;
var urlReq:URLRequest=new URLRequest(url);
var loader:URLLoader=new URLLoader;
loader.addEventListener(Event.COMPLETE,completeHandler);

function completeHandler(event:Event):XML {
XML.ignoreWhitespace=true;
var loadedXML:XML = new XML(event.target.data);
loader.close();
loader.removeEventListener(Event.COMPLETE,completeHandler);
isLoaded = true;
return loadedXML;
}
urlReq.method=URLRequestMethod.POST;
urlReq.data=urlVars;
urlVars.action=action;
loader.load(urlReq);
xml = XML;
}
}

public class TestPanel extends MovieClip {

var loadList:ListLoader = new ListLoader();

public function TestPanel() {
//trace("ftp panel instantiated");
filters=[dropShadow];
fmt.size=11;
fmt.color=0x524B47;
fmt.font="AGBookBQ-Regular";
fmt.tabStops=[170,290];
loadList.getList("http://www.somedomain.com/somescript.php", "listAll");
addEventListener(KeyboardEvent.KEY_DOWN, enterKeyDownHandler);
var loadedIntervalID = setInterval(checkListLoad, 1000);

function checkListLoad() {
if (loadList.isLoaded == false) {
//keep checking
trace("still not loaded");
} else {
trace("loaded");
clearInterval(loadedIntervalID);
}
}


function processXML(xml:XML) {
var record:String=new String;
for each (var item in xml.record) {
record+= item.company + " ";
record+= item.un + " ";
record+= item.pw + "
";
}
//trace(record);
ftpMainTxt.htmlText=record;
ftpResultTxt.setTextFormat(fmt);
}
}

Passing Variables Between Classes
Can someone tell me how I can pass a varible between one class to another?
What I have is a list of videos (FLV) and when I click on a video name (button) I want the menu page to close, open another page (the video interface page) and play the video that was chosen. I do not want the video to play on the menu page but on it's own interface page. I am guessing I will need to save the String name in an outside file for the video class to grab. Once the video has finished playing I want to go back to the menu page.

Passing MovieClips Through Classes
Hello, folks!

I have a hard difficult using classes in Flash. The question is: How can I attach movie clips through classes ?

For example: I have a class to do a clip like an excel table:

So, I have a Cell class (Celula.as), a Columm (Coluna.as) and the final table (Tabela.as).

Here they are:

Cell:

Code:
class Celula {

private var superID:Number;
private var grupo:String;
private var texto:String;
private var conteiner:MovieClip;


function Celula() {
superID = new Number();
grupo = new String();
texto = new String();
conteiner = new MovieClip();
}

// setters:
public function setDataProvider(id:Number, g:String, t:String):Void {
this.superID = id;
this.grupo = g;
this.texto = t;
trace("superID: "+this.superID + newline + "grupo: "+this.grupo + newline + "texto: "+this.texto + newline + "--------------");
}



// getters:
public function getSuperID():Number {
return this.superID;
}
public function getGrupo():String {
return this.grupo;
}
public function getTexto():String {
return this.texto;
}

private function getClip():MovieClip {
var mc:MovieClip = this.conteiner.attachMovie("celula_mc", "celula"+superID, superID);
mc.rotulo_txt.htmlText = this.getTexto();
return mc;
}

}

Columm, wich imports the Cell class..

Code:
import Celula;
class Coluna {



private var grupo:String;
private var celula:Celula;
private var arrCel:Array;
private var conteiner:MovieClip;



function Coluna() {
this.grupo = new String();
this.celula = new Celula();
this.arrCel = new Array();
}


public function setColuna(g:String, no:XMLNode):Void {
this.createColuna(g,no);
}

public function getCelulas():Array {
return this.arrCel;
}

public function getCelulaAt(i:Number):Celula {
return this.arrCel[i];
}
public function getGrupo():String {
return this.grupo;
}
public function getClip():MovieClip {
return this.conteiner;
}
private function createColuna(grupo:String, noColuna:XMLNode):Void {
var count:Number = noColuna.childNodes.length;
for(var i:Number = 0; i < count ; i++){
var celula:Celula = new Celula();
celula.setDataProvider(i, grupo, noColuna.childNodes[i].childNodes[0].firstChild.nodeValue)
arrCel.push(celula);
this.conteiner.attachMovie(this.arrCel[i].conteiner, "cel"+i, (i));
}
}
}
And, finally, the Table wich imports the Coluna.as Class


Code:
import Coluna;
class Tabela {

private var numColunas:Number;
private var larguraMaxima:Number;
private var arrColunas:Array;
private var conteiner:MovieClip;
private var coluna:Coluna;
//
// construtor:
function Tabela() {
numColunas = new Number();
larguraMaxima = new Number();
arrColunas = new Array();
coluna = new Coluna();
}
//
// setters:
public function setTabela(noXML:XMLNode):Void {
var totalColunas:Number = noXML.childNodes.length;
this.numColunas = totalColunas;
this.conteiner = _root.createEmptyMovieClip(noXML.attributes.nome, _root.getNextHighestDepth());
for (var i:Number = 0; i < totalColunas; i++) {
var cl:Coluna = new Coluna();
cl.setColuna(noXML.childNodes[i].attributes.grupo, noXML.childNodes[i]);
this.arrColunas.push(cl);
var mc:MovieClip = this.conteiner.attachMovie("celula_mc", "col"+i, this.conteiner.getNextHighestDepth());
}

}
public function attach():Void {
_root.createEmptyMovieClip("tabela", _root.getNextHighestDepth());
}
public function setLargMax(w:Number):Void {
this.larguraMaxima = w;
}
//
// getters:
public function getNumColunas():Number {
return this.numColunas;
}
public function getTabela():Tabela {
return this;
}
public function getArrColunas():Array {
return this.arrColunas;
}
public function getConteiner():MovieClip {
return this.conteiner;
}
}
So, my problem is: I do not know how to insert the Celula.as object into the Coluna.as object and insert the Coluna.as objects into the Tabela.as object.

Some one can help me with this?

Sorry for my poor english.

Tks!

pp

Passing Variables In Classes?
ok - really can't figure this out.

i'm trying to update arrays and get variables in function in a flash class. Problem is i just can't seem to find them!

could someone please explain how i access the different variables from different functions? Any pointers much appreciated as i need to understand this once and for all. mostly the ones with // after them.


Code:
class favs {

var totalFavs:Number = 0;
var userId:Number;

var favVids:Array;
var favIds:Array;

function testFunction() {
}
//
function addFav() {
totalFavs++;
var videoId = _level0.myFavs.videoId;
var iAmHere = this;

trace("add fav "+_level0.myFavs.videoId+" tot;"+totalFavs+" ui;"+userId);

var rgu = new LoadVars();
rgu.funcId = "addFav";
rgu.videoId = videoId;
rgu.userId = userId;
rgu.sendAndLoad("http://www.roguefilms.com/flashPHP/addFav.php",rgu,"POST");
rgu.onLoad = function(success) {
if (success) {

_level0.myFavs.userId = rgu.returnedUserId;
favVids.push(videoId); //doesn't add item to array
favIds.push(rgu.returnedVideoId); //doesn't add item to array
trace(favVids);//traces undefined
trace(favIds);//traces undefined

trace(rgu.returnedVideoId+" >>> "+userId+" ");


}
};
trace(favVids); //traces undefined
trace(favIds);//traces undefined

}
}

Passing Results Between Classes
Last edited by bob_300 : 2008-02-26 at 12:03.
























If I have two classes, and I want to pass a property from one into another what is the best way to do this? I have tried using extends and super on the other class but it isn't working.

Thanks!

Passing Variables Between Classes
I've just got my head around event broadcasting and listeners. I've managed to listen from one class to an event broadcast from another. But how in the name of god do I pass a variable along with the broadcast?

If anyone can at least point me in the direction of the answer I'll be most happy.

Thanks in advance.

Tricky Sliding Menu Problem - Classes Or Arrays?
I have a fairly complicated little actionscripting task (at least for me). I have to create a menu of movie clips that slide around and replace each other when clicked. So, say I had the following menu set up:

1 2 3 4

and someone clicked on "3"... the "3" movie clip would slide left to take the "1" clip's place, and "1" and "2" would slide right to make room. The new menu position would look like this:

3 1 2 4

Then, if someone clicked on "2", it would look like this:

2 3 1 4

All the while, these things have to expand and work as menus when they reach the left-most position. I've not seen any menus like this, and I can't find any open source AS samples to give me some idea how to do this. What I figure I need to do is set up some sort of class that has all the data I need for each movieclip:
what is it's current position in the "lineup"
what is it's X position
what is the movieclip we're dealing with
is the menu open or not)
And then have a script that shuffles them appropriately (heh... no problem, right? :-/) Right now what I have is this script:

---------------------------------
menuWidth = 320;
menuLeftOffset = 400;
numMenuItems = 6;
avgItemWidth = menuWidth/numMenuItems;

// level 1 arrays
clipNameArray = new Array("about","services","clients","work","people","contact");
startXPos = new Array(0, 53, 106, 159, 212, 265);

// create the menuObject class
function menuObject (posNum, xPos, clipName) {
this.posNum = posNum;
this.xPos = xPos;
this.clipName = clipName;
this.menuOpen = 0;
}

// make an array of 'em
menuArray = [];
for (x=0; x < numMenuItems; x++) {
menuArray.push(new menuObject(x,startXPos[x],clipNameArray[x],menuOpen[x]));
}
---------------------------------

and six separate movieclips (menuObj1 through menuObj6), each named with the name of the menu item... so the menuObj1 movieclip instance is named "about," the menuObj2 movieclip instance is named "services," etc.

What I can't figure out (don't know) is how to "attach" the class to each movieclip, so the movieclip itself contains its relative data and can be addressed as such. I'd like to be able to say something like:

if (menuObject[x].menuOpen = 0) {
// the menu is closed and we can move this one to the #1 position
-- do close current #1 menu
-- move menuObject[x] to the #1 position
-- move the other menuObjects over to fill the positions to the right.

Put another way, I want to be able to shuffle the class data and make the menu objects respond accordingly. Can anyone help me with this? This is pretty new territory for me.

Thank you immensely in advance! If you could respond via email, that would be great!

Matt
------
mlaurenc@theworld.com
www.mattlaurence.com

Need Advice On Passing Values Between Classes
this seems like on the most infuriating aspects of AS3. How is it done?

Particles: Passing Variables Between Classes
I'm creating a Class particle system/emitter that I want to have properties for, from which I can control them from within the main timeline of the main FLA

ParticleSystem is called to create the emitter, and inside that, Particle is created for each particle..

Here is the full codesee below for problem

ActionScript Code:
//ParticleSystem

package  {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.display.MovieClip;
    import flash.events.TimerEvent;
    import flash.utils.Timer;
   
    public class ParticleSystem extends Sprite {
       
        public var _xp:Number;
        public var _yp:Number;
        public var _xv:Number;
        public var _yv:Number;
        public var _g:Number;
               
        //the function used to make a system
        public function ParticleSystem() {
       
            var timer:Timer;
            timer = new Timer(200);
            timer.start();
            timer.addEventListener(TimerEvent.TIMER, onLoop, false, 0, true);
        }
       
        //make the particle
        private function onLoop(evt:TimerEvent) {
            var p:Particle = new Particle(_xp, _yp, _xv, _yv, _g);
            addChild(p);
        }
    }
}

ActionScript Code:
//Particle
package  {
    import flash.geom.*;
    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.utils.Timer;
    import flash.display.*;
   
    public class Particle extends Sprite {
        private var _xpos:Number;
        private var _ypos:Number;
        private var _xvel:Number;
        private var _yvel:Number;
        private var _grav:Number;
        private var timer:Timer;
       
        public function Particle(xp:Number, yp:Number, xvel:Number, yvel:Number, grav:Number) {
            _xpos = xp;
            _ypos = yp;
            _xvel = xvel;
            _yvel = yvel;
            _grav = grav;
           
            var ball:Sprite = new Ball();
            addChild(ball);
           
            x = _xpos;
            y = _ypos;
            alpha = .8;
            scaleX = scaleY = Math.random() * .5;
           
            timer = new Timer(50);
            timer.start();         
            timer.addEventListener(TimerEvent.TIMER, onRun, false, 0, true);
        }
       
        private function onRun(evt:TimerEvent):void {
            _yvel += _grav;
            _xpos += _xvel;
            _ypos += _yvel;
            x = _xpos;
            y = _ypos;
           
            if(_xpos < 0 || _ypos < 0 || _xpos > stage.stageWidth || _ypos > stage.stageHeight) {
                timer.removeEventListener(TimerEvent.TIMER, onRun);
                parent.removeChild(this);
            }
        }
    }   
}


PROBLEM


So I declare the properties:
ActionScript Code:
public var _xp:Number;
        public var _yp:Number;
        public var _xv:Number;
        public var _yv:Number;
        public var _g:Number;

Then pass them to the new Particle:


ActionScript Code:
//Within ParticleSystem.as

private function onLoop(evt:TimerEvent) {
            var p:Particle = new Particle(_xp, _yp, _xv, _yv, _g);
            addChild(p);
        }

Then they tie with the params in the Particle Class


ActionScript Code:
//Within Particle.as

public function Particle(xp:Number, yp:Number, xvel:Number, yvel:Number, grav:Number) {
            _xpos = xp;
            _ypos = yp;
            _xvel = xvel;
            _yvel = yvel;
            _grav = grav;
           
            var ball:Sprite = new Ball();
            addChild(ball);
           
            x = _xpos;
            y = _ypos;
            alpha = .8;
            scaleX = scaleY = Math.random() * .5;
           
            timer = new Timer(50);
            timer.start();         
            timer.addEventListener(TimerEvent.TIMER, onRun, false, 0, true);
        }

Then in the timeline I put this

ActionScript Code:
//Within animation.fla

var emitter:ParticleSystem = new ParticleSystem();
    addChild(emitter);
   
    emitter._xp = Math.random()*1000;
    emitter._yp = 0;
    emitter._xv = Math.random()*11-5;
    emitter._yv = Math.random()*1;
    emitter._g = .2;

So i'm using _xp, _yp, _xv, _yv, _g, as my properties for the particles, and for some reason I can't control from the flash file.

So my question is:

How can I pass the vars from the main class, into the second class, and control them from the timeline. I think I'm missing something, I've been working on this for awhile.

Passing Simple Variables Between Classes
Hello, again.

I have class doc A that enables the user to generate a variable (specifically, a uint for a bitwise color transform). I need this variable to be accessed by class B. I essentially need to reuse the color variable to shade another element in class B.

I am extremely new to variable passing (and AS 3.0 in general) so, don't assume I know the basics of variable passing. =-)

Thanks!

Passing Variables From Classes To Swfs
Hello all,

I'm having trouble passing variables from an class which is loading this data from an xml file to a swf that this class is also loading.

I want the swf file to use the some of the data contained in the main class.

At the moment I can' seem to see a way of doing this, I haven't used AS3 or Flash in a few months either which isn't helping.

I'm able to load the swf fine from the xml but I still haven't figured out how to compile the swf file without getting errors because the variables it needs are in the class...

Any help with a show in the right direction would be great.

Dave

Passing Arrays
I wrote a class that requires an array of sprites that it then assembles them into one sprite. In the timeline I instantiated the class and entered the array of sprites as a parameter, but I get an error #1010 "that an object is undefined and has no properties". Can an array be passed as a parameter?

Dispatching Events Between Classes And Passing Arguments
Hi everyone,

I've come to a dead end with this problem. I'm new to AS3 and very confused with event handling

I have 2 classes and one of them has to pass a color value to another one.

onClick I want an object to pass its color value to another object that is listening to that Click event.

Can someone post a simple solution to that? I'd be very very gratefull.

Thanks guys

Passing Values To Movie Clips Using Classes
Hi. I've created a movie clip and I've attached it to a custom class which in turn defines the onEnterFrame events and other variables.

In my understanding when you attach a new movie clip, it will call the constructor function of that movie clip.

My question is, how can I pass variables to the movie clip to be used by the constructor etc? Can I do:


attachMovie("newMC", "newMC1",1);
newMC.someVariable = 20;

when I try this, nothing happens. Any help most welcome!

Dispatching Events Between Classes And Passing Arguments
Hi everyone,

I've come to a dead end with this problem. I'm new to AS3 and very confused with event handling

I have 2 classes and one of them has to pass a color value to another one.

onClick I want an object to pass its color value to another object that is listening to that Click event.

Can someone post a simple solution to that? I'd be very very gratefull.

Thanks guys

Passing Arrays Via HTML Tag?
I know that variables can be set via HTML (such as movie.swf?var1=data&var2=moredata) but is it possible to pass Flash arrays this way?

e.g. movie.swf?array=["data1","data2","data3"]

I can't test at the moment, if anyone else knows or is able to try it can you post a reply please.

TIA

Leon

Passing Arrays Into Functions
Can I pass an array into a function by using a string variable to represent the array? For example:

myArray = new Array();

could myArray be represented as a string?

newValue = "myArray";

function myFunction(array){

temp = array;

trace(temp[0]);

}

myFunction(newValue);


this doesn't work, and I need to be able to pass a an array to a function, but I would like to do it by referencing the array using a string variable. Please help me!

Passing Arrays Into Functions
Ok, I don't think I explained my situation very well. I want to use a string variable of the same name as the array, to pass into a function. I need that string variable to be able to call the array.

I appreciate the help from before, it got me a little closer. I can find a way around, but this would be useful. Here is my code.

function cityPop(string){ // string represents the city's name
// which is also the array name I want to
// extract information from

_parent.city = string[0];// here "string" represents the
_parent.pop = string[1]; // array's name

}

is there some method which will turn the string being passed into a form which will allow it to be evaluated as an array?

Thanks in advance!

Passing Arrays Into Flash
Hi,

Is there a simple way to pass an array into Flash?

I have a database that I want to query.
I need the results of the query passed into an array in Flash.

I'm using Flash MX 04, SQL DB, and ASP.

My Process is currently as follows:

I've got a DB in SQL with data.

I'm using ASP to query the database and return the results.
In asp, I'm formatting a string of variables -
&item1=a|b|c&item2=d|e|f&item3=g|h|i and so forth

In Flash I'm using LoadVariablesNum and pointing to the asp page.
I parse the string so that item1's data will be in array[0], item2's data will be in array[1] and so forth.

The data to be passed into flash is a bit long so the strings are quite long.

Is there an easier way to do what I am doing?

Thanks.

Passing Arrays To Functions
I'm having trouble sending an array to a function. Maybe someone could help.

For example:

function makeArray()
{
test =
[
[ "category1","item1","item2" ],
[ "category2","item1","item2" ]
];

displayArray(test);
}

function displayArray(array)
{
trace(array[0][2]);
}


It just displays "undefined"

Thanks in advance.

Passing Arrays To Flash From PHP
Hi

I need to let my admin guy enter dates into external files for my calendar in my swf to load onto an events calendar.

The events calendar is actually more of a timeline, and these dates will place dots on the timeline.

Any ideas on the best way to do this??

Thanks a lot,

Chris
http://emma.dar.cam.ac.uk/~cdj21/smrtj/aru

Passing Arrays To Packages
I really need to sit down and sort out referencing in packages... it's really holding me back from using them.

Could anyone please explain how a private function in my external package can reference an array declared in a frame script on the main timeline of my fla?

And is this the correct way to um, call(?) my package from a frame script:


Code:
var InstigateNewDock:Dock = new Dock();
It certainly triggers all the traces in the Dock class. Should I perhaps pass the array I want to use here?

Passing Arrays As A Variable
So, i'm sure i'm making this harder than it really is, but this is my problem. I have a very simple image gallery and I'm creating next & previous buttons.. I've created an array for these buttons and it works perfectly. the only problem is when i send the output of the array to my function it doesn't recognize it as a variable.

these are the actions for my buttons
nextBTN.onRelease = function() {
++pos;
if (pos>6) {
pos = 1;
}
_root.currentImage = ["image"+pos];
//i'm trying to get the array to output image# as a variable
trace(_root.currentImage);
_root.loadImage();
};
prevBTN.onRelease = function() {
--pos;
if (pos<1) {
pos = 1;
}
_root.currentImage = ["image"+pos];
trace(_root.currentImage);
_root.loadImage();
};
these are in a mc called imageViewerMC
on the main timeline is where i have my loadImage function and it loads my images into the loader component.
function loadImage() {
imageViewerMC.loader.load(currentImage);
}
the variable currentImage is established by each thumbnail button, and there it works fine. i.e. ignore the rest, just focus on the red.
tn1.onRelease = function() {
imageViewerMC.preloader._visible = true;
if (_root.imageViewerMC._currentFrame == 15) {
currentImage = image1;
imageViewerMC.pos = 1;
loadImage();
} else {
imageViewerMC.gotoAndPlay("open");
currentImage = image1;
imageViewerMC.pos = 1;
checking = setInterval(checkLabel, 1000);
}
};
and each variable there is defined before as a url,
so image1="/folder/folder/58980-13890-181.jpg";
image2="/folder/folder/489027-18900.jpg";
so on and so forth.


Like i said the array works fine and when I trace the output of the array i get the correct text "image#" whatever the next image is, but.. here's my problem. loader tries to load that as the url instead of reading it as a variable. when i'm just loading the variable from the thumbnail buttons it works fine, but from the array it doesn't recognize it as a variable. how do i fix this?

Passing Arrays To An Jsp File
Last edited by Flexbaby : 2005-02-14 at 05:57.
























Ey all, i have a problem when im trying to parse an array to an jsp file... im Parsing both variables and arrays, and the variables is getting parsed perfectly. When im parsing the array it ses the array as an string/variable and not an array...

im using LoadVars,

ActionScript Code:
var userCreate = new LoadVars();
    userCreate.interessArr = new Array();
    for (i=0; i<interesseArray.length; i++) {
        userCreate.interessArr[i] = interesseArray[i];
    }
   
   
    userCreate.firstname = _root.one.txtholder.firstname;
etc
etc
userCreate.sendAndLoad("user_create_commit.jsp", userCreate, "POST");


Hope this makes sense

Passing Objects With Arrays
i made a dataload class for my flash site which loads a php page and creates an object with arrays in (news, menu, bio, ...).
I can make the dataload object and get the object witth everything in
but from the moment I pass my object from my dataload class to the timeline I can't access the arrays in the object (everything is accessible in the class itself)

I find it strange that I can't pass an object with arrays in it to the timeline in a proper manner


ActionScript Code:
var pierot_obj:dataTous = new dataTous("php/tous_pierot.php");
var alles = pierot_obj.getDataObject();


when i trace alles.mmenu (the array with menu items) i get undefined
but when i trace the same in my dataTous class (dataload) I get the array with menu items

this is how i pass teh object to the timeline

ActionScript Code:
public function getDataObject():Object {
        return xmlDataObject;
    }

Passing Arrays To And From Shared Objects
I have two arrays in my frame 1 root timeline

clips[menu,middle,background,bottom]
colours['0x336666', '0xCC9933', '0x1234cc', '0x1111BB']

When a user clicks on certain buttons it adds colors to the colours array, at specific places

on(release){
colours[1]=0x123456
}

on(release){
colours[3]=0x546534
}

etc, etc

Several buttons will add colour value elements to the array

When the user hits the 'save' button the 'colours' array should be saved on his computer as a saved object (.sol) for the sake of arguments called 'scheme'

When the user returns, the array elements he saved should be loaded into the colours array.

How should I do this?

Passing Images Through Loaded Swf's Via Arrays(FUN)
HI

here is the thing, my company has asked me to amend some code it got which to say is complex is an understatement and will not run when exported as flash player 7

The Brief
To make a fully dynamic swf that can go into a forenamed folder count the amount of jpegs in it import them and fire them into this complex code that makes a magazine. it will be online, and there potentially could be alot of jpegs long download, all jpegs must be fully loaded before entering magazine.

Now the script on Frame 1 to import the images, name them and build an array is...
code:
var count = 0;
var intMaxPages = 20;
var objListener = new Object();
var objLoader = new MovieClipLoader();
var pageOrder = new Array();

objListener.onLoadComplete = function(target_mc){
//pageOrder.push(["page" + count]);
var strSeperator = "";

if (target_mc._url.indexOf("\") > 0){
strSeperator = "\";
} else {
strSeperator = "/";
}

var strPagename = target_mc._url.split(strSeperator)[target_mc._url.split(strSeperator).length-1];

//strPagename = strPagename.split(".")[0];

pageOrder.push(strPagename);

trace("image Loaded for page " + strPagename);
}

objListener.onLoadError = function(target_mc, errorCode) {
trace("Removing move " + target_mc);
target_mc.removeMovieClip();
}

objLoader.addListener(objListener);



while(count<= intMaxPages){
this.createEmptyMovieClip("page"+ count, 10*count);
this["page" + count]._x= 801;
//loadMovie("pageImages/page" + count + ".jpg", this["page" + count]);
objLoader.loadClip("pageImages/page" + count + ".jpg", this["page" + count]);

count++;
}


obviously this is using the MovieClipLoader.loadClip() which is flash player 7 only and as I said before the other code will not run in 7

So.. I exported the "pageflip_empty.swf"as version 6.
After the code above runs through this loader check on frame 2 on an empty movieclip is

code:
onClipEvent (enterFrame) {
trace("check me out man " + _parent.pageOrder.length);
if (_parent.pageOrder.length == undefined) {
_parent.gotoAndPlay(2);
} else {
_parent.gotoAndPlay(3);
}
}


I' ve done this as the images were not loading in time and not populating the array.

The code on frame 3 then loads the "pageflip_empty.swf"

code:
trace("this is the page" + pageOrder);
loadMovie("pageflip_empty.swf", "magholder_mc");

stop();


So we have an swf(Flash player 7)that imports images from a folder, counts how many there are, checks if they are fully loaded and then imports an swf(flashplayer 6)...which then need to import the jpegs via an array called pageOrder via attachMovie!
now if you follow all that WELL DONE!

NOW THE PROBLEM

the array passes through to the "pageflip_empty.swf" but the jpegs that loaded need to be passed/pathed through "pageflip_empty.swf" so that it can be used via attachMovie

please dont tell me to put them in one swf unless you have a piece of code that does all of the above whilst exported in flash player 6



I am totally stuck ANY THOUGHTS WILL BE GRAND!

Problems With Passing Parameters And Arrays---- Please Help :s
Hello everyone!
I'm kinda new to actionscript programming and currently i'm making a very small photo album. in this photo album, i have thumbnails and a main view area. i have actually achieved making it but the coding i have done is not really suitable.. like it's very long.. i'm trying to use arrays to achieve the same task which results in shorter coding.

well first, here is the code i programmed firstly which works perfectly:

ActionScript Code:
///////////////////////////////////////////////
var opened:Object = new Object();
var top:Number;

// "mc1..2..3" are the pictures in the library
// "f1...2...3" are shapes where the pictures are set to their positions/scales

this.attachMovie("mc1","mc1",this.getNextHighestDepth());
mc1._height= f1._height;
mc1._width= f1._width
mc1._x= f1._x;
mc1._y= f1._y;
this.attachMovie("mc2","mc2",this.getNextHighestDepth());
mc2._height= f2._height;
mc2._width= f2._width;
mc2._x= f2._x;
mc2._y= f2._y;
this.attachMovie("mc3","mc3",this.getNextHighestDepth());
mc3._height= f3._height;
mc3._width= f3._width;
mc3._x= f3._x;
mc3._y= f3._y;
this.attachMovie("mc4","mc4",this.getNextHighestDepth());
mc4._height= f4._height;
mc4._width= f4._width;
mc4._x= f4._x;
mc4._y= f4._y;
this.attachMovie("mc5","mc5",this.getNextHighestDepth());
mc5._height= f5._height;
mc5._width= f5._width;
mc5._x= f5._x;
mc5._y= f5._y;
this.attachMovie("mc6","mc6",this.getNextHighestDepth());
mc6._height= f6._height;
mc6._width= f6._width;
mc6._x= f6._x;
mc6._y= f6._y;

//user clicks on the thumbnail to view enlarged picture.

mc1.onRelease= function(): Void {
   
    view("mc1");
};
mc2.onRelease= function(): Void {
   
    view("mc2");
};
mc3.onRelease= function(): Void {
   
    view("mc3");
};
mc4.onRelease= function(): Void {
   
    view("mc4");
};
mc5.onRelease= function(): Void {
   
    view("mc5");
};
mc6.onRelease= function(): Void {
   
    view("mc6");
};



function view (slink:String):Void {
   
       
    if (opened[slink] != undefined ) {
        opened[slink].swapDepths(top);
        return;
    }
    var index:Number = this.getNextHighestDepth();
    var mcPic:MovieClip = this.attachMovie(slink, "mcPic"+ index, index);
    opened[slink]=mcPic;
    top=index;

//mcView is a simple shape where the picture is positioned and scaled on it

    mcPic._height= mcView._height;
    mcPic._width= mcView._width;
    mcPic._x= mcView._x;
    mcPic._y= mcView._y;

}

///////////////////////////////

well.. i hope my comments help you there to understand the code. sorry i'm not very used to commenting my codes lol as i'm new to flash.

as you can see the code "above" is very repetative so i thought i could use arrays to short it down.

the following is the new code i been working on, which partly works. the part that works is the thumbnails.. but when i click on them..nothing happens :s .. i'm not sure how to send an array of parameters to the function "view()"... please help:

/////////////////////////////////////////////////////

ActionScript Code:
var opened:Object = new Object();
var top:Number;
var myPics:Array = new Array("mc1", "mc2", "mc3", "mc4", "mc5", "mc6");
var myArray:Array= new Array(f1, f2, f3, f4, f5, f6);


for (var i:Number=0; i< myPics.length; i++){
var mc:MovieClip = this.attachMovie(myPics[i], "mc"+ i, i);
var mov:Array= new Array (mc0, mc1, mc2, mc3, mc4, mc5);
mov[i]._height= myArray[i]._height;
mov[i]._width= myArray[i]._width;
mov[i]._x= myArray[i]._x;
mov[i]._y= myArray[i]._y;

mov[i].onRollOver= function():Void {
    this._alpha=70;
};
mov[i].onRollOut= function():Void {
    this._alpha=100;
};
///// everything works fine up to here//////////

mov[i].onRelease= function(): Void {

////i'm pretty sure this is where the problem is----->> view(mov[i])
        view (mov[i]);
};

}

//// in here consider --->>slink:MovieClip .... should i be using a diff var type?

function view (slink:MovieClip):Void {
    mcPic.removeMovieClip();
    if (opened[slink] != undefined ) {
        opened[slink].swapDepths(top);
        return;
    }
   
    var index:Number = this.getNextHighestDepth();
    var mcPic:MovieClip = this.attachMovie(slink, "mcPic"+ index, index);
    opened[slink]=mcPic;
    top=index;
   
    mcPic._height= mcView._height;
    mcPic._width= mcView._width;
    mcPic._x= mcView._x;
    mcPic._y= mcView._y;
}

////////////

any small help would be a great help to me.. I'd really really appreciate it

thanks

Passing Arrays Back To Flash
Hi All,

I am currently using PHP to retrieve content from a database dynamically, I have been successfull in generating basic text content and then displaying it in the swf, now I need to pass data back to Flash so that Flash recognises it and puts it in array...

Ive tried passing the data back as:
- stores[0]=bla bla abla&stores[1]=blalblablba
- stores=blablablbla&stores=blablabla

but they dont work...

Is this possible?

Thanks,
Craig

Passing Arrays With Objects To A Function
I am working with the 3D engine in one of the tutorials, but I am expanding one of the functions to have an Array with objects as a parameter:

Code:
backAndForthAndSideToSide = function (pointsArray:Array) {
var screenPoints = new Array();
for (var i = 0; i<pointsArray.length; i++) {
var thisPoint = pointsArray[i];
if (direction == "left") {
thisPoint.y -= speed;
if (i == pointsArray.length-1 && thisPoint.y<=-150) {
direction = "backward";
}
} else if (direction == "backward") {
thisPoint.z += speed;
if (i == pointsArray.length-1 && thisPoint.z>=150) {
direction = "right";
}
} else if (direction == "right") {
thisPoint.y += speed;
if (i == pointsArray.length-1 && thisPoint.y>=150) {
direction = "forward";
}
} else if (direction == "forward") {
thisPoint.z -= speed;
if (i == pointsArray.length-1 && thisPoint.z<=-150) {
direction = "left";
}
}
With the array:

Code:
MakeA3DPoint = function (x, y, z) {
var point = new Object();
point.x = x;
point.y = y;
point.z = z;
return point;
};
MakeBox = function (Num, Width, Depth, Height) {
_root.createEmptyMovieClip("box"+Num,Num);
Points = new Array();
Points = [[-Width/2, -Height/2, -Depth/2], [Width/2, -Height/2, -Depth/2], [Width/2, -Height/2, Depth/2], [-Width/2, -Height/2, Depth/2], [-Width/2, Height/2, -Depth/2], [Width/2, Height/2, -Depth/2], [Width/2, Height/2, Depth/2], [-Width/2, Height/2, Depth/2]];
for (i=0; i<Points.length; i++) {
Points[i] = MakeA3DPoint(Points[i][0], Points[i][1], Points[i][2]);
}
return Points;

};
this.pointsArray2 = _root.MakeBox(2,80, 80, 80);
box.onEnterFrame = backAndForthAndSideToSide(pointsArray2);
Thank you to any insight you can provide,

Passing Arrays From Text File
Hi all,

Can someone give me an idea on how to do the above? I am able to trace the values but it appears that it is parsed as a big chunk of string like

"apple","orange","pear"

etc

so when I tried to assign the value to an array with:

myArray = [fruits]

instead of becoming:

myArray = ["apple","orange","pear"]

instead of being able to trace(myArray[1]) to yield "orange", I get undefined

really at my wits end so can someone help me?
tks!

Passing Arrays With Objects To A Function
I am working with the 3D engine in one of the tutorials, but I am expanding one of the functions to have an Array with objects as a parameter:

Code:
backAndForthAndSideToSide = function (pointsArray:Array) {
var screenPoints = new Array();
for (var i = 0; i<pointsArray.length; i++) {
var thisPoint = pointsArray[i];
if (direction == "left") {
thisPoint.y -= speed;
if (i == pointsArray.length-1 && thisPoint.y<=-150) {
direction = "backward";
}
} else if (direction == "backward") {
thisPoint.z += speed;
if (i == pointsArray.length-1 && thisPoint.z>=150) {
direction = "right";
}
} else if (direction == "right") {
thisPoint.y += speed;
if (i == pointsArray.length-1 && thisPoint.y>=150) {
direction = "forward";
}
} else if (direction == "forward") {
thisPoint.z -= speed;
if (i == pointsArray.length-1 && thisPoint.z<=-150) {
direction = "left";
}
}
With the array:

Code:
MakeA3DPoint = function (x, y, z) {
var point = new Object();
point.x = x;
point.y = y;
point.z = z;
return point;
};
MakeBox = function (Num, Width, Depth, Height) {
_root.createEmptyMovieClip("box"+Num,Num);
Points = new Array();
Points = [[-Width/2, -Height/2, -Depth/2], [Width/2, -Height/2, -Depth/2], [Width/2, -Height/2, Depth/2], [-Width/2, -Height/2, Depth/2], [-Width/2, Height/2, -Depth/2], [Width/2, Height/2, -Depth/2], [Width/2, Height/2, Depth/2], [-Width/2, Height/2, Depth/2]];
for (i=0; i<Points.length; i++) {
Points[i] = MakeA3DPoint(Points[i][0], Points[i][1], Points[i][2]);
}
return Points;

};
this.pointsArray2 = _root.MakeBox(2,80, 80, 80);
box.onEnterFrame = backAndForthAndSideToSide(pointsArray2);
Thank you to any insight you can provide,

Passing Javascript Arrays To Flash Array? PLEASE HELP ME DEAR GOD
is there a way to create an array (in javascript), and pass it to an array in flash? everytime i try, it gets to flash as a string of values, not as seperate values, each in it's own array slot.


thanks - matt

Passing Array Variables Into Functions (and Why I'm Hopeless At Arrays)
OK, I have spent a day on this now and have done some fairly extensive searching online. The problem is - I am hopeless with arrays (and probably just actionscript generally for that matter)

I want to create an array of buttons, so I set up an array of actions, step through each item and then try to pass that array action into an onclick button for an attached button

The problem I have is that the onclick function ALWAYS returns the last item in the array.

Help!

Code below:

----------------------------------------------------------------







Attach Code

//set up array
var myArray:Array = new Array("action1","action2","action3");
// for each item in the array
for (var i:Number = 0; i < myArray.length; i++) {
var myArrayNode = myArray[i];
myArrayIndex = i+1;
var myButton:MovieClip = attachMovie("workIndexBtn", myArrayIndex, this.getNextHighestDepth());

//ignore -- offset each button by 100px
myButton_x = myArrayIndex*100;
myButton._x = myButton_x;
//end ignore

//action button for each item in the array with correct action
myButton.onRollOver= function() {
trace(myArrayNode); //always returns action3
};
}

Custom Classes: One Class Tracks Multiple Other Classes?
I'm working on a coloring that allows kids to place objects on a scene and then color them so the image can be printed out. So assume you have sky background, the child can select a bird object, drag it into place and once they have it in place, color everything on the page (with a given palette of colors.)

So far it going great. However I want to track what objects have been added to the drawing on the fly. I have a potential solution using arrays but I'm thinking this is perfect opportunity to start using custom classes.

I'm thinking that I'd create a new instantiate a copy of the object class each time an object is added to the scene. However to track the objects added to the scene I'm thinking I'll also use an listing class to track them.

What I'm not sure about is the would the listing class simply contain an array of object identifiers? Any thoughts on the structure of the listing class?

I'm very new to oop as I've mainly been doing procedural programming up to this point but I'm eager to give this a shot.

Thanks!

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