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




[F8] First Class Variable Troubles



I'm trying to get a class working in ActionScript 2 and having real problems

hopefully someone can help me with the following code

class library.classes.XML_Loader {
var _file:String;
var data_xml:Object;
var i:Number;
var _targetText:String;
var target:String;
var sortItOut:String = "sorted";
//
public function XML_Loader(file,targetText) {
_file = file;
_targetText = targetText;
}
public function update() {
trace("loading xml file = " + _file);
data_xml = new XML();
data_xml.ignoreWhite = true;
data_xml.onLoad = loadData;
data_xml.load(_file);
//
function sendData() {
trace("this is..." + sortItOut);
}

function loadData(success) {
trace("xml loaded");
data_xml = this.toObject();
trace(data_xml.siteMenu.button.length);
target = "button_";
for(i=0; i<data_xml.siteMenu.button.length +1; i++) {
_root[target + i]._textField.text = data_xml.siteMenu.button[i-1].buttonLabel;
}
}
//

XML.prototype.toObject = function () {
var $xparse = function (n) {
var o = new String (n.firstChild.nodeValue), s, i, t
for (s = (o == "null") ? n.firstChild : n.childNodes[1]; s !=
null; s = s.nextSibling) {
t = s.childNodes.length > 0 ? arguments.callee (s) :
new String (s.nodeValue)
for (i in s.attributes) t[i] = s.attributes[i]
if (o[s.nodeName] != undefined) {
if (!(o[s.nodeName] instanceof Array)) o
[s.nodeName] = [o[s.nodeName]]
o[s.nodeName].push (t) }
else o[s.nodeName] = t }
return o }
return $xparse (this)
}
}
}

The problem is that i can't get info (variables) into (or out of) the loadData(success) function.

I've tried just about every workaround i can think of, but this time i'm well and truly stumped.

One solution would be to move the for-loop out of the function, but then it doesn't recieve the xml to spread around the site.

Thanks in advance to anyone who can shed some light on this!



FlashKit > Flash Help > Flash ActionScript
Posted on: 09-10-2006, 09:56 AM


View Complete Forum Thread with Replies

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

First Class Variable Troubles
double submit-

1000 apologies

Class Troubles...
I'm experimenting with classes and i'm getting a bit annoyed cuz flash can't load my class file.

I set the class of one of the movie clips to "Enemies" and here's the code for "Enemies.as"

Code:
class Enemies{
var myhealth:Number
var mytype:String
function displaystuff(){
trace("I'm a "+mytype +" enemy and i have "+myhealth +" health left")
}
}
but, whenever i preview the movie in flash it says "The class or interface 'Enemies' could not be loaded."
why? i have flash 8, if it helps

Class Troubles.
I have a file: CurrencyConverter.fla which I have exported to CurrencyConverter.swf. In it is 1 frame with the ASv2 of:


ActionScript Code:
import MyTesting.CurrencyConverter;
 
var rate:Number = 0.634731;
var converter:CurrencyConverter = new CurrencyConverter(rate);
 
var result:Number = converter.convert("ISD", 130.5);
trace(result);


I have a folder called MyTesting in the CLASSPATH. Inside it is a file called CurrencyConverter.as.

The ASv2 in that file is:


ActionScript Code:
class CurrencyConverter {
    var exchangeRate:Number;
   
    function CurrencyConverter(rate:Number){
        exchangeRate = rate;
    }
 
    function convert(convertTo:String, amount:Number):Number {
        var result:Number;
        if (convertTo == "USD") {
            return amount / exchangeRate;
        } else if (convertTo == "GBP") {
            return amount * exchangeRate;
        }
    return result;
    }
}


Thanks to a previous post, I'm using the SE|PY AS Editor (since FMX2K4 doesn't come with one) and I'm gettin an error in this class file of:

Syntax Error: unexpected token IDENT expecting ASSIGN or ++ or -- at line 1

When I run the Flash Movie I get:

**Error** C:Documents and SettingsamartoneLocal SettingsApplication DataMacromediaFlash MX 2004enConfigurationClassesMyTestingCurrencyConverter.as: Line 16: Syntax error.
}

Total ActionScript Errors: 2 Reported Errors: 2

undefined

Any ideas guys?

[F8] Tween Class Troubles
I'm using the Tween class to fadeIn, Pause, and fadeOut an image in Flash 8.

I have functions that work in a loop - loadImage function triggers fadeIn triggers Pause triggers fadeOut triggers loadImage etc...

This is all working dandy. However, I want to be able to click a thumbnail and whatever tween it's doing should stop, and jump to the fadeOut function, which would then call the load function, starting the process over. What's actually happening when I click the thumbnail is it does jump to fadeOut, but the other tween doesn't stop, so I now have multiple loops going on (like Row, Row, Row Your Boat in staggered choruses).

I've tried giving the instances of myTween different names, I've tried myTween.stop(), but it doesn't help. I just keep getting competing function loops.

Any suggestions?

Thanks

[F8] Tween Class Troubles
Hey all,

So I am working on a project in which I need to move objects dynamically using actionscript. Basically there are 60 instances of the same card which you can click on (they are named card 1-60) and that card which you have clicked needs to move to a specified spot on the stage.

Within the card MC is a button that gets a few variables on click; it gets the name of which card was clicked and stores it as a variable, as well as which card in sequence you have clicked (after you choose 6 cards, something else happens.)

Anyway, in the card MC code it also activates a function on the Root timeline, which SHOULD input the name of the card clicked as a variable, as well as its X and Y position, and move it to a certain spot on the stage (I haven't worked out where yet, I just want to get it to move SOMEWHERE for now). Here is my code so far:


PHP Code:



var thisCardPosX;
var thisCardPosY;

function moveCard() {
             trace(thisCardPosX);
    import mx.transitions.Tween;
    import mx.transitions.easing.*;
    var xPosT:Tween = new Tween(thisCard, "_x", Regular.easeInOut, thisCardPosX, 0, 1, true);
    var yPosT:Tween = new Tween(thisCard, "_y", Regular.easeInOut, thisCardPosY, 0, 1, true);
    xPosT.onMotionFinished = function() {
        trace("moveDONE!");
    };
    yPosT.onMotionFinished = function() {
    };
}




It doesn't work! I'm not sure why. Am I using the tween class wrong? From what I can tell it SHOULD be moving the card from its current position (the variable is changed with the code inside the card's MC, it traces properly at least) to 0 on the stage (top left.) It doesn't even move! Please help!

Register Class Troubles
hi there,

I got a class called NPC, which has a method called goToRoom:


PHP Code:



public function goToRoom(dest:String):Void {
        trace(this.name + " going to " + dest);
        this.room.unloadNPC(this);
        var rm:RoomManager = RoomManager.getInstance();
        var r = rm.getRoom(dest);
        this.mc = r.loadNPC(this);
        this.mc.setArgs(this.name);
    }




the room attribute is a reference to an instance of the Room class. the unloadNPC method, clears the npc from the current room it is in atm. With the String dest I load the NPC in the Room with String dest. loadRoom is a method of the Room class, which is printed out below. setArgs is a method of a class called ClickableNPC. This class is a class that makes an instance of the graphical appearance of the NPC class.


PHP Code:



public function loadNPC(npc:NPC):MovieClip {
        var mc_ref:MovieClip;
        for (var i:Number = 0; i < this.ptNPC.length; i++) {
            if (this.ptNPC[i].npcSet == false) {
                mc_ref = this.ptNPC[i].attachMovie(npc.getMC(), "npc" + i, this.ptNPC[i].getNextHighestDepth());
                trace("loaded cnpc " + npc.getName());
                var ref:Object = new Object();
                ref.mc = mc_ref;
                ref.id = npc.getID();
                this.npcArray.push(ref);
                this.ptNPC[i].npcSet = true;
                npc.setRoom(this);
                break;
            }
        }
        return mc_ref;
    }




In this method I create a var called mc_ref. I attach a movieclip to this var. The linkage to the movieclip is a movieclip which is registered to the ClickableNPC class. So when I load an NPC its graphical appearence (ClickableNPC instance) is loaded to a point of the ptNPC array. Then I return the ClickableNPC. But here's the issue; the setArgs method, uses the parameter of the last created ClickableNPC to all other ClickableNPC's. other then that the classes work perfectly, all other events and methods of the ClickableNPC work properly. The args parameter is written to a non-static variable of the ClickableNPC class. Anybody has an explination for this strange behavior?

I Have Troubles Wit A Document Class
Hi there.

I have a FLA file where I'm using two frames, in the first one I have just some simple code, but in the second frame I need to use a Document Class because I have a MP3 player that use all the classes in that document.

This document works perfectly when I use only one frame, but when I add a frame before the MP3 player crashes.

If you have any idea, please let me notice.

See you later.

Class Troubles - Sequencer
hi i'm currently trying to create a sequencer class for use with loops

basically the problem is that when the choose loop function is run from the onSoundComplete function it runs, but the _sequence array is undefined and i dont know why

here is my class
Code:

class com.alexpitman.Sequencer extends Array {
   private var _sequence:Array;   
   private var currentLoop:Object;
   
   private var output:Sound;
   
   public function Sequencer() {
      _sequence = this;
   }
   
   private function chooseLoop() {
      var r:Number = Math.floor(Math.random()*_sequence.length);
      currentLoop = _sequence[r];
      var repeats:Number = currentLoop.rep[Math.floor(Math.random()*currentLoop.rep.length)];
      
      output = new Sound();
      
      output.onSoundComplete = chooseLoop;
      
      output.attachSound(currentLoop.loop);
      output.start(0, repeats);
   }
   
   public function start():Void {
      chooseLoop();
   }
}


here is my fla code
Code:

import com.alexpitman.Sequencer;

var s:Sequencer = new Sequencer();
s.push({loop:"loop1", rep:[2, 4]});
s.push({loop:"loop2", rep:[2, 4]});
s.start();


there are two mp3's in the library with loop1 and loop2 export names
i've kind of set it up like the fuse engine

any help?

[F8] Help Please Can A Class Have An Array As A Property? Having Troubles.
Okay, the pertinent information at the start of the class:


PHP Code:




class Ship extends MovieClip {
//private variables
private var _gridsize
private var _gridrow:Number = 0;
private var _gridcol:Number = 0;
private var _health:Number = 9;
//public variables
public var movequeue:Array = Array();
public var beingmoved = false;
public var _facing:Number = 90;
.....







I left in a bunch of the internal variables just so people can see how I was declaring and initializing them.

The problem is with the movequeue property/variable. I have tried declaring it with 'new Array()' at the end as well.

What is happening is that later on in the class file I have method that pushes a value into the moveque. Stripped down, the problem part is:


PHP Code:




private function move1() {
this.movequeue.push("somevalue")
}







In my main code the problem is that after this function call, all my classes of type 'Ship' are assigned the same movequeue.

So if I had ship objects 'playership' and 'playership2', if I did this:


PHP Code:




playership.move1()
trace(playership.movequeue)
trace(playership2.movequeue)







They would both trace "somevalue".

Is my error that you just can't have an array as a property in a class? Because it is a class itself? But a string and a number are classes in AS as well, aren't they?

I am confused and very annoyed.

I was debugging the wrong part of the code for about 2 hours over this issue until I found out that it was the rather simple act of doing the push itself was where the problem was cropping up.

Please help, this is driving me nuts!

Printjob Class Scalability Troubles
Yesterday, I made my first effort in flash printing. The first thing I read about was the functionality of the right click menu and printing. That was easy to have working in no time flat. It prints perfectly. I love the absence of browser defined margins.

But I want to use the PrintJob class, and in no time, I had the code working. But when I hit print (my button), the printout is about 25% wider than what I'd like and no use of pageheight, paperheight, and the like have made any difference.


Code:
PrintButton.onRelease = function() {
var my_pj:PrintJob = new PrintJob();
var myResult:Boolean = my_pj.start();
my_pj.paperHeight = 792 // 11 (inches) x 72 (pixels)
my_pj.paperWidth = 612 // 8 x 72
my_pj.pageHeight = 400 // Movie Height
my_pj.pageWidth = 682 // Movie Width
if(myResult) {
this.visible = false; // hide print button from frame
my_pj.addPage(0); // Adding the sole frame to print
my_pj.send();
}
delete my_pj;
};
I also initially tried it without the paper and page dimension settings. Same result.

Variable Troubles
I have programming exp in many languages, but I am fairly new to flash and am having some trouble getting my variables to work.

Here is the scenario...
I have the main movie with a menu bar comprised of 7 buttons, and a body which is a seperate movie loaded into level 2. When you click on a button I have the script set variable 'button' equal to 'buttonName' (depending on which button) and then it loads a transition movie into level 3.

The transition movie is just a sliding graphic that covers the body on level two. Then the script:
First: unloads level 2 (I am not sure if this is the most elegant way to do this , but it seems to work.)
Second: uses a series of 'if' and 'elseif' statements to check and see which button was clicked.
if(button==buttonName){load movie for that response into level 2}
elseif(button==buttonName2){load movie for that response into level 2}
etc.... would have liked to use a switch, but could not find a switch action....
Third: unloads level 3 ....the transition graphic


my problem is that no matter which button I use it always loads the movie clip for the first button in the series of if /elseif statements. This laeds me to believe that there is some kind of problem with these statements.

I have used if statements for years and cannot see any reason why they shouldn't work, but it is human to err, and I am new to flash so I could use some help.please!thanks!

Variable Name Troubles
Hello, in my movie, when a user clicks a button, I have the following code:
on(release){
if(ownership!=true){
loadMovie("owner.swf",3)
company=false;
procedures=false;
ownership=true;
clients=false;
cities=false;
}

}

on another button, I have the following code:
on(release){
if(company!=true){
loadMovie("company.swf",3)
company=true;
procedures=false;
ownership=false;
clients=false;
cities=false;
}

}

and on the 1st frame of the timeline, I have this code:

ownership=false;
procedures=false;
clients=false;
cities=false;
company=false;
stop();



What I want is for it to check to see if the variable is not true, and if it is true, not to load the swf, but if it is not true, to load the swf into level 3. The movie works correctly at first, but it only will do the action once, then it is just stuck on the same swf. any help?



thanks alot


Greg

Variable Name Troubles
Hi all, this is going to be hard to explain so bear with me
I have a function that duplicates a movieclip 15 times and then does some tweening etc. It names the duplicates 1_1, 1_2, 1_3 etc. I have another function that takes the same 15 clips and tweens them out so to speak, then calls the first function again. I want the out tween to overlap the next in tween so my thought was to change the name of the clips each time the main function starts. so second time round the clips would be 2_1, 2_2, 2_3 etc. Trouble is I'm using a variable to change the name and because I'm using that variable to target the clips for tweening, it changes the out clips names to be the same as the new ones mid tween, thus buggering things up. LOL I'm tired, sorry for the crappy explanation. Is there a way to rename a variable? or should I look for a different solution altogether?

Hope that made sense

Cheers,

jr.

Variable Troubles ?
I've been searching and fiddling for hours to try and get this scenario working :-

Index page with a top flash button bar.
To the right of the button bar the buttons sit, to the left, the heading of the related page sits.

This is a movie instance called "header"

I can get everything working so that when I click on a button, it changes the movie header, it works wonderfully.

Now, when I reload the webpage, the header resets itself back to blank.

My problem is that I want it to remember the last button pressed and when the webpage is reloaded, the flash will automatically play the correct header.

So, I set a variable called "clickme" - when I press one of the buttons it sets the variable - for instance, the profile button sets the value to "profile", like so :-


Quote:





on (rollOver) {
_root.profile.gotoAndPlay(2);
_root.buttonback.gotoAndStop(2);
}
on (press) {
clickme = "profile";
_root.profile.gotoAndStop(10);
_root.header.gotoAndPlay("profile");
getURL("content-profile.htm", "content");
}
on (rollOut) {
_root.profile.gotoAndPlay(11);
_root.buttonback.gotoAndStop(1);
}






You'll see a two lines down from the variable, the normal action that the button does to the header movie instance - I need to replicate that when the webpage with buttons is loaded, however, it must replay the correct bit of my header animation - so I need to set a variable.

I only have one frame in my _root movie as everything is done via movie instances.

On that first frame, I've put the following code :-

header.gotoAndPlay(clickme);

But it doesn't work - it never picks up the variables set by the button.

However, the following works :-


clickme = "profile";
header.gotoAndPlay(clickme);

the value of clickme is a frame name - it's just a more efficient way than having to use multiple if statements.

Why is it that my buttons won't set the variable, or rather, that the gotoAndPlay action won't read them ?

Variable Troubles
Here is my code...can anyone assist me in determining why the variable value is not being passed to the movie clip control line...line 9. Any suggestions would be GREATLY appreciated!!

var horVal:Number = 1;
var vertVal:Number = 1;
var imVisible:MovieClip = movie1_mc;

imageHold_mc.attachMovie ("movie1", imVisible, this);

sliderHor.horSlider = function (horOnSlide) {
horVal = Math.round(horOnSlide*35) + 1;
imageHold_mc.imVisible.gotoAndStop(horVal);
trace (_root.imVisible);
trace (horVal);
}
sliderVert.vertSlider = function (vertOnSlide) {
vertVal = Math.round(vertOnSlide*24) + 1;
_root.imVisible = ("movie" + vertVal + "_mc");
imageHold_mc.attachMovie ("movie" + vertVal, "movie" + vertVal + "_mc", this);
}

Thanks!!







Attach Code

var horVal:Number = 1;
var vertVal:Number = 1;
var imVisible:MovieClip = movie1_mc;

imageHold_mc.attachMovie ("movie1", imVisible, this);

sliderHor.horSlider = function (horOnSlide) {
horVal = Math.round(horOnSlide*35) + 1;
imageHold_mc.imVisible.gotoAndStop(horVal);
trace (_root.imVisible);
trace (horVal);
}
sliderVert.vertSlider = function (vertOnSlide) {
vertVal = Math.round(vertOnSlide*24) + 1;
_root.imVisible = ("movie" + vertVal + "_mc");
imageHold_mc.attachMovie ("movie" + vertVal, "movie" + vertVal + "_mc", this);
}

Variable Troubles
Hello, how do I 'post' a new variable to a movieclip from the main timeline or a different movieclip?

var MC.newVar:Number = 3;/*newVar does not exist in MC... but I want to add it (I knew this code method wouldn't work... just trying to demonstrate what I want)*/


Thanks, Jake

External Class Files - Importing Troubles...
I'm working on modifying an open source flash chart (teethgrinder.co.uk) ... I'm having some trouble reaching variables..

The file structure looks like this..

open-source-chart.fla

the only AS is on frame 1 of the timeline and it reads:

import open-source-chart.as

that file doesn't import anything else..

Problem is, it came packages with lots of other AS files... that are mysteriously being imported???

How is this possible???

I'm asking because I'm trying to reach a variable in open-source-chart.as from the file tooltip.as ...

Is that even possible?

Help very much appreciated! Thanks!

Extended Movieclip Class - Moviecliploader Troubles
Greetings:

I've extended the movieclip class, via the library/attachMovie. I'm also loading images
into movieclips on the fly, and need onRollover and onRollout functionality. Here's the
deal: I can access properties and methods of the extended class just fine outside of
the listener.onLoadInit function, but can't access them within:

var mclListener:Object = new Object();
var img_mcl:MovieClipLoader = new MovieClipLoader();
this.attachMovie("extend_mc", "test_mc", this.getNextHighestDepth());
//ExtendMC is the subclass of MovieClip - makes no difference
//to pass target_mc as a MovieClip or an ExtendMC...
mclListener.onLoadInit = function(target_mc:ExtendMC):Void {
target_mc.onRelease = function() {
trace("The on release event worked, however:");
trace("Within the listener, the extended movieclip' test_str property is "+target_mc.test_str);
target_mc.test_fn();
};
};
img_mcl.addListener(mclListener);
img_mcl.loadClip("lemon2.jpg", test_mc);
trace("Outside of the movieclip loader, test_str is "+test_mc.test_str);
test_mc.test_fn();

The class looks like:
class ExtendMC extends MovieClip {
public var test_str:String = "Able to access the test_str property.";
public function test_fn(Void):Void {
trace("Able to access the test_fn property");
}
public function ExtendMC() {
// constructor
}
}

Any ideas about how to make methods and properties of the ExtendMC class
visible within the listener functions?

Thanks

Accessing A Text Box From An External Class In CS3 Troubles.
So I'm going through some tutorials on the site, specifically the MP3 player originally done in Actionscript 2. I've run into a bit of a problem though, I'm trying to update a text field on my stage named pathDisplay.

I have a package with a public class name ZENPlayer from with in my class I have a function that I'm using to move through an array of tracks. I would like to update the text field from with in this same function, but I can't seem to directly access the text field. I get an error 1120: Access of undefined property pathDisplay.

I can set a variable and then call that variable from the main timeline and set the text box text that way but not directly from the AS file is self.

Here's my code:

In my AS file:
Code:

package {
   
   public class ZENPlayer{
      
      import flash.net.URLLoader
      import flash.net.URLRequest
      
      public var ZPVolume:uint = 10;
      public var ZPTrack:String = "";
      public var ZPCurTrack:uint = 0;
      public var ZPPath:Array;
      public var ZPSongList:Array;
      public var ZPSongDisplay:String = "";

      public function playSong():void{
         ZPSongDisplay = ZPPath[ZPCurTrack];
         pathDisplay.text = ZPSongDisplay;
      }
      
      //Move to the next MP3 in the list
      public function playNext():void{
         if(ZPCurTrack == ZPPath.length - 1){
            ZPSongDisplay = ZPPath[ZPCurTrack];
            pathDisplay.text = ZPSongDisplay;
         }else{
            ZPCurTrack++;
            ZPSongDisplay = ZPPath[ZPCurTrack];
            pathDisplay.text = ZPSongDisplay;
         }
      }
      
      //Move to the previous MP3 in the list
      public function playPrev():void{
         if(ZPCurTrack == 0){
            ZPCurTrack = ZPPath.length - 1;
            ZPSongDisplay = ZPPath[ZPCurTrack];
            pathDisplay.text = ZPSongDisplay;
         }else{
            ZPCurTrack--;
            ZPSongDisplay = ZPPath[ZPCurTrack];
            pathDisplay.text = ZPSongDisplay;
         }
      }
   }
}

My problem is the line:

Code:

pathDisplay.text = ZPSongDisplay;

I know that the ZPSongDisplay is set because I can trace it out.

I have a dynamic text field on the main stage with the instance name pathDisplay but I keep getting the error:

1120: Access of undefined property pathDisplay.

Any ideas?

Thanks,
Steve

Variable/Targeting Troubles
I have three buttons on the stage (buttonOne, buttonTwo and buttonThree), three animations (animationOne, animationTwo and AnimationThree) and the following code in frame 1 of the main timeline:


Code:
var activeButton:MovieClip = null; ///

buttonOne.addEventListener (MouseEvent.MOUSE_OVER, overHandler);
buttonOne.addEventListener (MouseEvent.CLICK, clickHandler);
buttonTwo.addEventListener (MouseEvent.MOUSE_OVER, overHandler);
buttonTwo.addEventListener (MouseEvent.CLICK, clickHandler);
buttonThree.addEventListener (MouseEvent.MOUSE_OVER, overHandler);
buttonThree.addEventListener (MouseEvent.CLICK, clickHandler);


function overHandler(event:MouseEvent) {

var target:String = event.currentTarget.name.substr (6);
var targetAnimation:MovieClip = MovieClip (getChildByName("animation" + target));
targetAnimation.gotoAndPlay ("fadeIn");
}

function clickHandler(event:MouseEvent) {

if (activeButton != null) {
activeButton.mouseEnabled = true; ///
}

var target:String = event.currentTarget.name.substr (6);

var targetAnimation:MovieClip = MovieClip (getChildByName("animation" + target));
targetAnimation.gotoAndStop ("active");

var targetButton:Object = Object (getChildByName("button" + target));
targetButton.mouseEnabled = false;

activeButton = targetButton;///
}
I'm having issues with changing the info held by the variable activeButton. The code utilizing the variable has been marked by "///". Trying to make the jump to AS3 so any input on all aspects of the code would be appreciated.

I think my issue is in the output provided by event.currentTarget and being used to AS2 to easily compile information held by a variable...but I was probably sliding on non-perfect code...because is I delete ":MovieClip" after where the variable "activeButton" is initiated the code works, but I read it's bad practice to do this.

Global Variable Troubles
This code seems to look fine but doesn't work, and it's not a path problem.


ActionScript Code:
if (_global.playCheck=false) {
    _root.showcaseClip.titleOneInstance.play();
    _root.showcaseClip.titleTwoInstance.play();
    _root.showcaseClip.titleThreeInstance.play();
    _global.playCheck = true;
} else if (_global.playCheck != false) {
    this._parent.titleInstance.play();
}
stop();


It's acting like it's not reading the variable correctly. Oh and yes I did use _global.playCheck = false; to set the variable in another movie.

Thanks in Advanced.

Duplicated MovieClip/variable Troubles
Hi,
I need my Flash MX application to have a varying number of input boxes to put their data into so I created a movie clip with an embedded input text box.

On creation the duplicated MC names itself "line"+i and then names the textbox's variable "answer" + i. (where i is an increasing integer.

So the path to first one is _root.line1.answer1,
second one is
_root.line2.answer2 etc.

Problem comes when I want to extract that data into a variable on the root level, as Flash doesn't like a path name like this:

_root."line"+i."answer"+i


Any ideas?

I Am Having Some Troubles To Pass A Variable From A Mclip To Another.
Hello

I am having some troubles to pass a variable from a mclip to another.
I am duplicating a mclip. Every mclip is a button that opens another mclip.
It’s like a contact list. When the user clicks a name a pop up mclip appears with more information’s. The problem is how the popup will appear the correct information’s
I am getting the records from a database.
Please help!
Thank you



Code:


var mcArray = new Array();
_root.mcArray = Array('asdfg', 'fffffff', 'ggggg', 'eeee', 'jjjjjj', 'qqqqqq', 'cvbn', 'tttttt', '1234', 'nbnbn');


this.createEmptyMovieClip("my_mc", 0);



function mclips(shapevar:MovieClip, cor:String, Y0:Number):Void {
var shapevar:MovieClip = _root.my_mc.attachMovie("row", cor, _root.my_mc.getNextHighestDepth());
shapevar._x = 270; //270
shapevar._y = Y0; //40



}

YY = 40;
for (i=0; i<10; i++) {
var nmclip:String = 'myclip' + i;
var mmm = nmclip;
mclips(shape, nmclip, YY);
YY = YY +30

_root.my_mc["myclip"+i].texta.text = mcArray[i];


_root.my_mc["myclip"+i].btn_mc.onPress = function():Void {

var box:MovieClip = _root.attachMovie("box", "cora", _root.getNextHighestDepth());
_root.cora.textb.text = mcArray[i];

box._x = 270;
box._y = 140;

}


}

I Am Having Some Troubles To Pass A Variable From A Mclip To Another.
Hello

I am having some troubles to pass a variable from a mclip to another.
I am duplicating a mclip. Every mclip is a button that opens another mclip.
It’s like a contact list. When the user clicks a name a pop up mclip appears with more information’s. The problem is how the popup will appear the correct information’s
I am getting the records from a database.
Please help!
Thank you



Code:


var mcArray = new Array();
_root.mcArray = Array('asdfg', 'fffffff', 'ggggg', 'eeee', 'jjjjjj', 'qqqqqq', 'cvbn', 'tttttt', '1234', 'nbnbn');


this.createEmptyMovieClip("my_mc", 0);



function mclips(shapevar:MovieClip, cor:String, Y0:Number):Void {
var shapevar:MovieClip = _root.my_mc.attachMovie("row", cor, _root.my_mc.getNextHighestDepth());
shapevar._x = 270; //270
shapevar._y = Y0; //40



}

YY = 40;
for (i=0; i<10; i++) {
var nmclip:String = 'myclip' + i;
var mmm = nmclip;
mclips(shape, nmclip, YY);
YY = YY +30

_root.my_mc["myclip"+i].texta.text = mcArray[i];


_root.my_mc["myclip"+i].btn_mc.onPress = function():Void {

var box:MovieClip = _root.attachMovie("box", "cora", _root.getNextHighestDepth());
_root.cora.textb.text = mcArray[i];

box._x = 270;
box._y = 140;

}


}

Variable Data Type Troubles
Hoping someone can help me with this, I'm sure it's something simple but I'm stumped!

Basically, I've got a map where each country is it's own Movieclip. I'm changing the tint on each country based on an attribute from the XML file which is called "status". I'm storing the status in a variable. The status is either "red" "green" or "yellow".

I was hoping I could then just use that variable value in the color change class, I've got variables of the same name there. The tint change works when I type in the variable red green or yellow but if I instead replace it with my countryColor variable which stores the value of status from the XML, it fails due to data type.

Basically, no matter what I try, I can't seem to get the color change class to recognize the string format. I tried changing the variable to type Color but that returns a null result.

Any help is greatly appreciated. Here is my non-working code!


ActionScript Code:
// Change color class //
import fl.motion.Color;
import flash.geom.ColorTransform;

//load xml//
var myXML:XML = new XML();
var XML_URL:String = "data.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener("complete", xmlLoaded);

//define Countries
var austriaColor:String;

// change the status colors
function xmlLoaded(event:Event):void
{
    myXML = XML(event.target.data);
    trace("Data loaded.");
    trace("Num countries is " + myXML.country.length());
    trace("country #2 is " + myXML.country[1].@name);
    austriaColor = myXML.country[1].@status;
    trace(myXML.country[1].@name + " = " + austriaColor);
}


/* red */
var red:Color = new Color();
red.setTint(0xFF0000, 0.9);
/* yellow */
var yellow:Color = new Color();
yellow.setTint(0xFFFF00, 0.9);
/* green */
var green:Color = new Color();
green.setTint(0x00CC00, 0.9);

mcAustria.transform.colorTransform = austriaColor;

Static Class Variable Referencing Class Instance
I was given the task of writing a class that would send serial requests for xml data, the idea being that the requests could be added while previous requests were still in progress, but the class would queue them and wait for the reply of one request to come back before sending the next.

The way I did this was to create a class instance for each request, and the request itself would be stored in an instance variable, waiting to be sent. A static variable called queue (accessible to all instances) was then given a reference to the instance, and when this reference got to the top of the queue, queue would call the sendRequest() method on that instance.

The reason why I am using one instance per request is so that the replies can be retrieved via the instance, so keeping each request entirely discreet.

Everything works very nicely, but the problem is my IT manager looked at the code and told me that you cannot put a reference to a class instance in a class static variable... and for this reason he has informed my line manager that he has serious reservations about the code, and recommends that it is not incorporated it into the project. However, the code works very well on my local machine and on the testsite, and no-one has experienced any problems with it.

Can someone reassure me here... I can see absolutely nothing wrong with having a class static array hold references to each of the instantiated class instances. And the proof is in the pudding.. it works. Can anyone else see a problem here?

How Do I Access A Variable Declared In My Document Class From Another Class
Hi there,

I'm pretty new to classes and am probably missing something really basic so apologies if this seems like a stupid question.

I'm trying to access a variable that I've declared in my document class from within another class.

I know I can pass the variable through when I call the class as follows:


Code:
var myBall:Ball = new Ball(5);
and pick this up in the Ball function within my Ball class as follows:


Code:
public function Ball(ballSpeed) {
trace(ballSpeed);
}
But what if I don't want to do that as I have a whole load of general global variables I want to access which were defined in my document class?

What I actually want to do is just have access to all the variables defined in the document class from within the Ball class.

I tried parent.variableName and various other ways of accessing what I need but all of them spit back errors.

Any help would be really appreciated - I'm sure this is very basic but I'm totally stuck on this.

Many thanks.
Ian

Problem Assiging Class Variable To The Main Timeline Variable .... PLEASE HELP
Hi Guys

I just can't seem to solve this problem!!!

I have a random class that generates a random image and an id number from an xml file and a main class that reads information from an xml file according to the id number.

I'm having trouble assigning my random id number from my class to the _root.id variable on the main timeline for my other class to read. I keep getting undefined???

Random Class Code:


Code:

import mx.utils.Delegate;
class randomClass {

public var target_mc:MovieClip;
private var _xml:XML;
private var myTotal:Number;
private var random_number:Number;
public var myFid:Number;
private var myPic:String;
private var myTitle:String;

private var myImages:Array = new Array();
private var myTitles:Array = new Array();
private var myFids:Array = new Array();
function randomClass(url:String, target:MovieClip)
{
target_mc = target;
_xml = new XML();
_xml.ignoreWhite = true;
_xml.onLoad = Delegate.create(this, onLoadEvent);
_xml.load(url);
}

function onLoadEvent(success:Boolean):Void
{
if (success)
{
var i:Number;

myTotal=_xml.firstChild.childNodes.length;

for(i=0; i<=myTotal-1; i++)
{
myImages[i]=_xml.firstChild.childNodes[i].firstChild.firstChild;
myTitles[i]=_xml.firstChild.childNodes[i].firstChild.nextSibling.firstChild;
myFids[i]=_xml.firstChild.childNodes[i].firstChild.nextSibling.nextSibling.firstChild;
}

random_number=random(myTotal);

myPic="<A href="http://www.mydomain/images/"+myImages[random_number">http://www.mydomain/images/"+myImages[random_number];
myTitle=myTitles[random_number];
myFid=myFids[random_number];

target_mc.title.text=myTitle;

var TheMovieLoader = new MovieClipLoader();
TheMovieLoader.loadClip(myPic, target_mc.new_mc);

var pictureLoaderListener = new Object();
pictureLoaderListener = TheMovieLoader.onLoadComplete()
{
target_mc.new_mc._x=-9;
target_mc.new_mc._y=-5;
target_mc.new_mc._xscale=40;
target_mc.new_mc._yscale=40;
}
TheMovieLoader.addListener(pictureLoaderListener);
target_mc.random_id.onPress = Delegate.create(this, onPressEvent);
}
}

public function onPressEvent() {
_root.id=myFid; //Undefined
trace(myFid); //ok
}
}

Main Movie Code:


Code:

on (press) {
var Obj:myClass=new myClass("<A href="http://mydomain/fanbase.xml",_root.viewer">http://mydomain/fanbase.xml",_root.viewer, _root.id);
}
It just keeps saying undefined but yet i seem to be able to trace myFid

Any ideas???

Thanks in advance

Problem Assiging Class Variable To The Main Timeline Variable .... PLEASE HELP
Hi Guys

I just can't seem to solve this problem!!!

I have a random class that generates a random image and an id number from an xml file and a main class that reads information from an xml file according to the id number.

I'm having trouble assigning my random id number from my class to the _root.id variable on the main timeline for my other class to read. I keep getting undefined???

Random Class Code:


Code:

import mx.utils.Delegate;
class randomClass {

public var target_mc:MovieClip;
private var _xml:XML;
private var myTotal:Number;
private var random_number:Number;
public var myFid:Number;
private var myPic:String;
private var myTitle:String;

private var myImages:Array = new Array();
private var myTitles:Array = new Array();
private var myFids:Array = new Array();
function randomClass(url:String, target:MovieClip)
{
target_mc = target;
_xml = new XML();
_xml.ignoreWhite = true;
_xml.onLoad = Delegate.create(this, onLoadEvent);
_xml.load(url);
}

function onLoadEvent(success:Boolean):Void
{
if (success)
{
var i:Number;

myTotal=_xml.firstChild.childNodes.length;

for(i=0; i<=myTotal-1; i++)
{
myImages[i]=_xml.firstChild.childNodes[i].firstChild.firstChild;
myTitles[i]=_xml.firstChild.childNodes[i].firstChild.nextSibling.firstChild;
myFids[i]=_xml.firstChild.childNodes[i].firstChild.nextSibling.nextSibling.firstChild;
}

random_number=random(myTotal);

myPic="<A href="http://www.mydomain/images/"+myImages[random_number">http://www.mydomain/images/"+myImages[random_number];
myTitle=myTitles[random_number];
myFid=myFids[random_number];

target_mc.title.text=myTitle;

var TheMovieLoader = new MovieClipLoader();
TheMovieLoader.loadClip(myPic, target_mc.new_mc);

var pictureLoaderListener = new Object();
pictureLoaderListener = TheMovieLoader.onLoadComplete()
{
target_mc.new_mc._x=-9;
target_mc.new_mc._y=-5;
target_mc.new_mc._xscale=40;
target_mc.new_mc._yscale=40;
}
TheMovieLoader.addListener(pictureLoaderListener);
target_mc.random_id.onPress = Delegate.create(this, onPressEvent);
}
}

public function onPressEvent() {
_root.id=myFid; //Undefined
trace(myFid); //ok
}
}

Main Movie Code:


Code:

on (press) {
var Obj:myClass=new myClass("<A href="http://mydomain/fanbase.xml",_root.viewer">http://mydomain/fanbase.xml",_root.viewer, _root.id);
}
It just keeps saying undefined but yet i seem to be able to trace myFid

Any ideas???

Thanks in advance

Problem Assiging Class Variable To The Main Timeline Variable .... PLEASE HELP
Hi Guys

I just can't seem to solve this problem!!!

I have a random class that generates a random image and an id number from an xml file and a main class that reads information from an xml file according to the id number.

I'm having trouble assigning my random id number from my class to the _root.id variable on the main timeline for my other class to read. I keep getting undefined???

Random Class Code:

Code:
import mx.utils.Delegate;
class randomClass {

public var target_mc:MovieClip;
private var _xml:XML;
private var myTotal:Number;
private var random_number:Number;
public var myFid:Number;
private var myPic:String;
private var myTitle:String;

private var myImages:Array = new Array();
private var myTitles:Array = new Array();
private var myFids:Array = new Array();
function randomClass(url:String, target:MovieClip)
{
target_mc = target;
_xml = new XML();
_xml.ignoreWhite = true;
_xml.onLoad = Delegate.create(this, onLoadEvent);
_xml.load(url);
}

function onLoadEvent(success:Boolean):Void
{
if (success)
{
var i:Number;

myTotal=_xml.firstChild.childNodes.length;

for(i=0; i<=myTotal-1; i++)
{
myImages[i]=_xml.firstChild.childNodes[i].firstChild.firstChild;
myTitles[i]=_xml.firstChild.childNodes[i].firstChild.nextSibling.firstChild;
myFids[i]=_xml.firstChild.childNodes[i].firstChild.nextSibling.nextSibling.firstChild;
}

random_number=random(myTotal);

myPic="<A href="http://www.mydomain/images/"+myImages[random_number">http://www.mydomain/images/"+myImages[random_number];
myTitle=myTitles[random_number];
myFid=myFids[random_number];

target_mc.title.text=myTitle;

var TheMovieLoader = new MovieClipLoader();
TheMovieLoader.loadClip(myPic, target_mc.new_mc);

var pictureLoaderListener = new Object();
pictureLoaderListener = TheMovieLoader.onLoadComplete()
{
target_mc.new_mc._x=-9;
target_mc.new_mc._y=-5;
target_mc.new_mc._xscale=40;
target_mc.new_mc._yscale=40;
}
TheMovieLoader.addListener(pictureLoaderListener);
target_mc.random_id.onPress = Delegate.create(this, onPressEvent);
}
}

public function onPressEvent() {
_root.id=myFid; //Undefined
trace(myFid); //ok
}
}
Main Movie Code:


Code:
on (press) {
var Obj:myClass=new myClass("<A href="http://mydomain/fanbase.xml",_root.viewer">http://mydomain/fanbase.xml",_root.viewer, _root.id);
}
It just keeps saying undefined but yet i seem to be able to trace myFid

Any ideas???

Thanks in advance

Reading Document Class Variable From A Class
I have a document class that establishes a variable called "_captioning". The document class then loads a button class that on attachChild needs to check to see if _captioning is set to true or false. I can load this class and can trace strings being generated inside the class but I can't target the _captioning variable outside of it in the document class.

I just need to see how I can get this button class to read things in the document class.

Using Variable Defined In One Class In Another Class, How?
hi everybody. i have a variable (holdFrame) in a class that controls a pause button, so that when the pause button is pressed, the variable stores the frame number where the pause button was pressed. pressing this button takes the timeline to a frame with nothing but the word "PAUSED" and a continue button on it. i have a class for the continue button that needs to call the variable that stored the previous frame number in it, so when the continue button is pressed the timeline is returned to the previous frame.

so how do i make that variable available to the other class and how do i call that variable from the other class? they are in the same package. below is the code for the two classes.

pause button code:

Code:
package lesson
{
import flash.display.MovieClip;
import flash.events.*;

public class PauseAll extends MovieClip
{
public var holdFrame:int;

public function PauseAll()
{
this.addEventListener(MouseEvent.CLICK, pauseAll);
this.buttonMode = true;
}

private function pauseAll(e:MouseEvent):void
{
holdFrame = MovieClip(parent).currentFrame;
MovieClip(parent).gotoAndPlay(MovieClip(parent).totalFrames);
}
}
}
continue button code:

Code:
package lesson
{
import flash.display.MovieClip;
import flash.events.*;
import lesson.PauseAll;

public class ContinueAll extends MovieClip
{

public function ContinueAll()
{
this.addEventListener(MouseEvent.CLICK, continueAll);
this.buttonMode = true;
}

private function continueAll(e:MouseEvent):void
{
MovieClip(parent).gotoAndPlay(MovieClip(parent).holdFrame);
}
}
}

[as2] Variable For A Class Name?
I'm trying to make an instance of a class based on a variable name, like so:

var cn:String = 'Foo';
var c = new cn(); // i didn't think this would work...

Where c would create an instance of class Foo. I've also tried:

var c = new eval(cn)();
or
var c = new eval('cn')();

and then:
var cn:String = 'Foo()';
var c = new eval(cn);

I've done this in php, but can't seem to get this to fly in actionscript...

Any ideas? Thanks in advance!

Is There Anyway To Use A Class As A Variable
okay I'm storing the type of class in a property of an object like this

enemy.projectileType = Laser;

and I'm wondering if there is code like this where I can create a class like this

var Projectile:Class = enemy.projectileType;
var projectile:Projectile = new Projectile();
this.addChild(projectile);

Why Is This Class Variable Not Getting... Set?
I don't get why one of these variables, which is set by a function in the class, is coming through as expected, while another variable, which is also set by a function in the class, is not. Why is it coming through as zero? It can't ACTUALLY be zero, because then all my images would be stacked up on top of each other, which they're not.




Code:
var mySlideShow = new FeaturedPanel("commercial");
trace(mySlideShow.slideShowRoot); // returns http://www.bencasey.co.uk/flash/images/commercial
trace(mySlideShow.slideShowWidth); //returns 0
FeaturedPanel.as

Code:
package com.ben.slideshow{

import flash.display.*;
import flash.events.*;
import flash.net.URLRequest;
import flash.net.URLLoader;

import com.pixelfumes.reflect.*

public class FeaturedPanel extends MovieClip{

private var _images:Array;
private var _bitmaps:Array;
private var _thumbs:Array;

private var _srv:URLRequest;//URL Service
private var _xmlLoader:URLLoader;//XML Loader
private var _xpos:Number = 0;//Used when placing the Images.
private var _slideShowRoot:String;

public var imageGap:Number = 5;//Gap (in px) between Images


public function get slideShowRoot():String{ return _slideShowRoot }
public function get slideShowWidth():Number{ return _xpos }

public function FeaturedPanel(slideshow:String){
super();
_images = new Array();
_bitmaps = new Array();
_slideShowRoot = "http://www.bencasey.co.uk/flash/images/" + slideshow;
_xmlLoader = new URLLoader();
_xmlLoader.addEventListener(Event.COMPLETE, buildGallery);
_xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, XMLLoadErrorHandler);
_srv = new URLRequest(_slideShowRoot + "/data.xml");
_srv.method = "GET";
_xmlLoader.load(_srv);
}


private function XMLLoadErrorHandler(errorEvent:IOErrorEvent):void{
trace("Error loading image list");
}


private function buildGallery(e:Event):void{

var xml:XML = new XML(_xmlLoader.data);

for each(var xmlImage:Object in xml.images.image){

var obj:Object = new Object();

obj.mainImagePath = String(xmlImage.file);
obj.thumbImagePath = String(obj.mainImagePath.replace(".jpg", "-t.jpg"));
obj.imageOrientation = String(xmlImage.orientation);
obj.imageCaption = String(xmlImage.caption);
obj.loader = new Loader();
obj.loader.contentLoaderInfo.addEventListener( Event.COMPLETE, imageCompleteHandler );

_images.push(obj);
}

var thisImageURL:String;
for each(var imageObj:Object in _images){
thisImageURL = _slideShowRoot + "/" + imageObj.thumbImagePath;
imageObj.loader.load( new URLRequest(thisImageURL) );
}
}


private function imageCompleteHandler(e:Event):void{

var bmp:Bitmap = Loader(e.target.loader).content as Bitmap;
bmp.width = 80;
bmp.height = 80;

_bitmaps.push(bmp);

if( _bitmaps.length == _images.length )
display();
}


private function display():void{

for each( var bmp:Bitmap in _bitmaps ){
placeBitmap(bmp);
}
this.x = (stage.stageWidth / 2) - (this.width / 2);
this.y = 10;
}


private function placeBitmap(image:Bitmap):void{

var thumb:FeaturedThumb = new FeaturedThumb(image);
thumb.x = _xpos;
thumb.buttonMode = true;

_xpos += image.width + imageGap;

this.addChild(thumb);

thumb.setRegistration(40, -10);

var ref:Reflect = new Reflect({mc:thumb, alpha:50, ratio:50, distance:0, updateTime:0, reflectionDropoff:.1});

thumb.init();
}



}

}

[as2] Variable For Class Name?
I'm trying to make an instance of a class based on a variable name, like so:

var cn:String = 'Foo';
var c = new cn(); // i didn't think this would work...

Where c would create an instance of class Foo. I've also tried:

var c = new eval(cn)();
or
var c = new eval('cn')();

and then:
var cn:String = 'Foo()';
var c = new eval(cn);

I've done this in php, but can't seem to get this to fly in actionscript...

Any ideas? Thanks in advance!

Getting A Variable From A Class
I have just created a class 'ClassA' that loads an XML file.Within that class I have a public function that navigates through the XML and populates arrays with the XML content.

I am now creating another class, which will be called 'ClassB' which I plan to extend 'ClassA'.

>From 'ClassB' I would like to reference the array variable (which is not in the constructor) to re-use in the 'ClassB' class. I have tried tons of different ways all of which I get undefined.

Could anyone help?

Cheers

[as2] Variable For Class Name?
I'm trying to make an instance of a class based on a variable name, like so:

var cn:String = 'Foo';
var c = new cn(); // i didn't think this would work...

Where c would create an instance of class Foo. I've also tried:

var c = new eval(cn)();
or
var c = new eval('cn')();

and then:
var cn:String = 'Foo()';
var c = new eval(cn);

I've done this in php, but can't seem to get this to fly in actionscript...

Any ideas? Thanks in advance!

Undefined Class Variable
Hi,

I have a class like this one:

PHP Code:



class Tank extends MovieClip {    
    var MyTank:MovieClip;
    var UserName:String = '';

    function Tank(_tank_id:MovieClip,_UserName:String){
        MyTank = _tank_id;
        UserName = _UserName;
        trace(UserName);
    }
    public function RunEngine() {
        trace(UserName);
    }
}




So, the first trace does work, but the secound one returns undefined.
But the Variable MyTank is working just fine.
I just dong get it. What am i doing wrong?
Hope you can help me, thank

Variable Scope In Class (AS 2.0)
I have a movie clip attached at runtime. I have a class linked to the movie clip. The movie clip is attached at root. All this works but check out how I am accessing the variables in the functions (ie: _parent.alphaon and _parent.alphaoff) Surely there must be a better way. Thanks for your comments.


Code:
//Constructor Function
function Screen() {
id = id;
path = _root["Screen"+id];
alphaon = 80;
alphaoff = 100;
setupdrag();
}

//Set Up Drag
function setupdrag() {

path.dragger.onPress = function() {
_parent.startDrag();
_parent._alpha = _parent.alphaon;
_parent.swapDepths(myDepth);
}

path.dragger.onRelease = function() {
stopDrag();
_parent._alpha = _parent.alphaoff;
}
}
}

[F8] Tween Class With A Variable?
Hello all,

Does anyone know if it is possible to use a variable with the canned tween classes in flash?

For example:

var myTween:Tween = new Tween(myVariable, "_x", Back.easeout, 100, 200, 1, true);

And don't worry...I have imported the necessary transition classes to make it work.

I basically want to use a variable, "myVariable", instead of a movieClip name. Does anyone know if this is possible?

Variable From A Class To The Documentclass ?
hello,

could someone please tell me how to send the variable "finished" back to the document class (after the fading is ready)? Is there an event to add or a dispatcherevent, how does that work?
Sorry if it's such a basic question...

This is part of the code in de class for the button:

private function actionButton (evt:MouseEvent)
{
this.addEventListener (Event.ENTER_FRAME, fadeOut);
}
private function fadeOut (evt:Event)
{
if (this.alpha >0)
{
this.alpha -= .1;
}
else
{
this.removeEventListener (Event.ENTER_FRAME, fadeOut);
finished = true;
return finished;
}
}

Thanks a lot in advance!
Jean-Francois

Variable Scope In Class
Hello,
I'm just getting started with OOP and writing classes. I've come across a problem. where Variables declared in the class are lost somewhere in the scope of things...

The static var X is'nt available to the method onBtn().. why? I'm probably missing something simple...


ActionScript Code:
class TestVars
{
    // reference to timeline
    var root:MovieClip; 
    // VARS
    var a:Number = 0;
    static var X:Number = 5;

    //constructor
    function TestVars(root:MovieClip)
    {
        this.root = root;
        init();
    }   
    // set up
    function init()
    {
        //  SET UP BUTTON 
        root.btnNext.scope = this;
        root.btnNext.onRelease = function()
        {
            this.scope.onBtn();
        }
       
        // START UP
        setVar(a);
    }
    //Set new variable 
    function setVar(t:Number)
    {
        a = t;
        trace('a: '+ a +' :'+ typeof(a))
    }   
           
       
    function onBtn()
    {
        trace('onBtn called: '+a+' + '+X+' = '+a+X) // TRACES: 0 + undefined = 0undefined   
        setVar(a + X);
    }
}

any help apreciated.
thanks

.henkedo

Class Variable Scope
I am trying to call an object's method in an event handler. It seems that the object was never defined.


Code:
// Main.as

class Main
{
var mc:MovieClip = null;
var b:Body = null;

static function main()
{
trace("main");

var m = new Main();
}

function Main()
{
trace("Main::Main");

this.mc = _root.createEmptyMovieClip("z00", 1);
this.b = new Body();

this.mc.onEnterFrame = this.onFrame;
}

function onFrame()
{
trace("Main::onFrame");
trace(this.b);
}
}

Code:
// Body.as

class Body
{
function Body()
{
trace("Body::Body");
}

function draw(mc:MovieClip)
{
trace("Body::draw");
}
}

Code:
// Output
main
Main::Main
Body::Body
Main::onFrame
undefined
Main::onFrame
undefined
Main::onFrame
undefined
...
Strangely, if I trace(this.mc) in Main::onFrame it is undefined also. The object that is generating the event is undefined?! I am going mad. Someone please help!

Super Class Variable
Is there a way in Actionscript 3 To create a variable in a super class that CANNOT be changed by any subclass that inherits the super class?

Possible To Call A Class The Same As A Variable?
I'm sorry if the topic sounds odd, but I don't know how else to word what I'm trying to do.

Basically think that you are getting a name/value pair of varibles from your server.

Now one of those name/pairs is called "className".

What I'm trying to do is get into a situation where I would make a new Class based on the className coming in.

For example: className=FunStuff&var=whatever&this=that

So I want to say "oh, alright, go ahead and fire off a new "FunStuff" and pass the variables with it.

What I've got so far is this:


ActionScript Code:
var serverVars:URLVariables = new URLVariables(event.data); //gets me my server vars

var InstanceClass:Class = getDefinitionByName(serverVars.className) as Class;
var classHolder:Object = new InstanceClass();

ReferenceError: Error #1065: Variable FunStuff is not defined.


Now the catch is that I don't want to have to define every single class that *could* come from the server ahead of time.

I thought that if I did something like:

ActionScript Code:
import projectfolder.*;

I would be able to access all the classes that are in that directory without explicitly calling them within the class first.

Hopefully that made sense to someone and they could guide me in the right direction of what to even search for.

Cheers

Reading A Variable From My Doc Class
Hi,

I just want to know how I can read a var from my doc class.


In my DocClass I have a variable called 'buttonIndex' how can I read this var from another external class ??

I think I kinda need the equivalent of _root to refrence the 'buttonIndex' var, all I want to do is read it for a condition in another class, the var is public.


HELP ME !!

_root Variable In Class
i want to pass _root variables to a component

how can i do that ?

this is a partial script from the component:








Attach Code

#initclip
trace(_root.test)
function calendarClass() {
this.cnt = 0;
this.init();
this.update();
}
Object.registerClass("calendar", calendarClass);
#endinitclip

AS 2.0 Can't Access A Variable In My Class
All my variables are set in the top of my class. But undefined if I trace them in my onenterframe function. Why he doesn't read them? What i do?








Attach Code

class clsAlbum {
var dragging:Boolean = false;
var friction:Number = 0.82;
var bounce:Number = 0;
var gravity:Number = 0;
var top:Number = 0;
var left:Number = 0;
var bottom:Number = Stage.height;
var right:Number = Stage.width;
var mvcAlbum:MovieClip;
var vx:Number = 0;
var vy:Number = 0;
var oldX:Number = 0;
var oldY:Number = 0;

function clsAlbum(mvc:MovieClip, object) {
vx = Math.random()*10-5;
vy = Math.random()*10-5;

mvcAlbum = mvc.attachMovie("mvcAlbum", "mvcAlbum"+object.number, mvc.getNextHighestDepth());
mvcAlbum._x = randRange(-10, 200);
mvcAlbum._y = randRange(100, Stage.height-mvcAlbum._height);
mvcAlbum._rotation = randRange(-40, 40);
mvcAlbum.onEnterFrame = function() {
if (!dragging) {
vy += gravity;
vx *= friction;
vy *= friction;
this._x += vx;
this._y += vy;
if (this._x+this._width/2>right) {
this._x = right-this._width/2;
vx *= bounce;
} else if (this._x-this._width/2<left) {
this._x = left+this._width/2;
vx *= bounce;
}
if (this._y+this._height/2>bottom) {
this._y = bottom-this._height/2;
trace(this._y);
vy *= bounce;
} else if (this._y-this._height/2<top) {
this._y = top+this._height/2;
vy *= bounce;
}
} else {
vx = this._x-oldX;
vy = this._y-oldY;
oldX = this._x;
oldY = this._y;
}
};
}
function randRange(min, max):Number {
var randomNum = Math.round(Math.random()*(max-min))+min;
return randomNum;
}
}

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