Problem With Getting The Values Out Of Class
HIThe problem is that I cannot get the value from class and then used it in textfield.I'm getting different values from XML file and one of them is name of current song.It works fine when I trace it inside of for loop which is inside xml.onLoad functionbut when I want to trace it outside of that xml.onLoad function it traces me undefined and the same result is in any other function...I don't know where is the problem. I'm sure it's my fault because this is my first class and I don't know much of it right now.If you have any idea what am I doing wrong please tell me.Thanks for nowmloncaric
Actionscript 2.0
Posted on: Mon Oct 23, 2006 8:55 pm
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
How Can A Child Class Pass Values To A Parent Class?
How can a child class pass values to a parent class?
Thanks to joshchernoff I've learned how to send events to a parent class and that works great. However I can't figure out how to pass values thru an event. Can anyone enlighten me?
Returning Values From A Class
is it possible, and any suggestions would be great, to have a base class (class 1) that adds a loader class (class 2) in which you feed it the file name, it does its loading thing then once complete returns the created array of images/text to class 1.
this has to be something that can be done and pretty simple, i am up for any advice here!
i understand return will return a value, but of course if you invoke that in class 1 it executes before the images/text has been loaded. does this make any sense??
Cheers in advance (any advice welcome :-)
Default Values In A Class
Hi guys
my question is simple, if I have a create a class I can either
a. Have some values set by the class itself as default or
b. Pass values to the class object at creation
what I want to be able to do is say only specify one, two, any or none of the values/properties at creation and then have the rest which weren't passed set to a default value
Is this possible an if so how?
Zen
Assining Values To An Array In A Class
Code:
class GetImages {
// Constants:
public static var CLASS_REF = GetImages;
public var imgXML:XML;
// Public Properties:
// Private Properties:
// declare private vars for image name and caption
private var newlyCreatedImgHolder_mc:MovieClip;
private var imgName:String;
private var imgCaption:String;
public var imageArray:Array;
private var captionArray:Array;
private var numOfItems:Number;
private var nodes:Number;
// Initialization:
public function GetImages() {
// instantiate new XML
imgXML = new XML();
//
imgXML.ignoreWhite = true;
imageArray = new Array();
captionArray = new Array();
imgXML.onLoad = function() {
nodes = this.firstChild.childNodes;
numOfItems = nodes.length;
trace(numOfItems+' images found');
for (var i = 0; i<numOfItems; i++) {
this.imageArray[i] = nodes[i].attributes.image;
trace('img array '+this.imageArray[i]+' '+i);
}
};
imgXML.load("xml/images.xml");
//
}
// Public Methods:
// Semi-Private Methods:
// Private Methods:
}
trace comes up like this;
6 images found
img array undefined 0
img array undefined 1
img array undefined 2
img array undefined 3
img array undefined 4
img array undefined 5
Any idea what I am doing wrong? Thanks, Dvl
Class Instances And Null Values
Hello all,
I'm currently stumped by this. I've created a class to load xml data from a txt file, then assign that xml to a variable named siteStructureXml. When I trace the value of siteStructureXml from within the class instance it shows the expected xml data. When I try to assign the value to a variable returnedXml defined on the timeline of my movie, it's value traces as null. I've a feeling it's something blindingly obvious...
The class is written as follows:
package uk.co.wearerevolting.initialisation
{
import flash.display.MovieClip
import flash.events.Event
import flash.net.URLLoader
import flash.net.URLRequest
public class XmlToVariableSetter extends flash.display.MovieClip
{
private var requestXmlUrl:URLRequest;
private var xmlFileLoader:URLLoader;
private var loadedXmlString:String;
public var siteStructureXml:XML;
public function XmlToVariableSetter()
{
}
public function loadXml():XML
{
requestXmlUrl = new URLRequest("site_structure.xml");
xmlFileLoader = new URLLoader(requestXmlUrl);
xmlFileLoader.addEventListener(Event.COMPLETE, assignXmlToVariable);
trace("loadXml value" + siteStructureXml);
return siteStructureXml;
}
public function assignXmlToVariable(event:Event):XML
{
loadedXmlString = xmlFileLoader.data;
siteStructureXml = XML(loadedXmlString);
trace("assign xml variable" + siteStructureXml);
return siteStructureXml;
}
}
}
The code on the timeline is:
import uk.co.wearerevolting.initialisation.*
var xmlSetter:XmlToVariableSetter = new XmlToVariableSetter();
var returnedXml:XML;
xmlSetter.loadXml();
returnedXml = xmlSetter.siteStructureXml;
trace(returnedXml);
Many thanks for your time
Accessing Values In Another Class's Constructor
Hey guys, I am working with a custom class in which the code is:
Code:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class XMLCache extends MovieClip {
public function XMLCache(myXML) {
var imagemap:XML = new XML(myXML);
var hotspot:XMLList = imagemap.child("hotspot");
var w:Number = imagemap.child("width")[0];
var h:Number = imagemap.child("height")[0];
var sw:Number = imagemap.child("stagewidth")[0];
var sh:Number = imagemap.child("stageheight")[0];
var allArgs:Array = new Array();
for (var i:Number = 0; i < hotspot.length(); i++)
{
var args:Array = new Array();
args[0] = hotspot[i].child("coordinates");
args[1] = hotspot[i].child("zoominto");
args[2] = hotspot[i].child("popupat");
args[3] = hotspot[i].child("id");
args[4] = hotspot[i].child("description");
var imgs:Array = new Array();
var imageList:XMLList = new XMLList(hotspot[i].child("image"));
for (var j:Number = 0; j < imageList.length(); j++) {
imgs[0] = imageList[j].child("source")[0];
imgs[1] = imageList[j].child("height")[0];
imgs[2] = imageList[j].child("width")[0];
imgs[3] = imageList[j].child("sequence")[0];
imgs[4] = imageList[j].child("title")[0];
}
args[5] = imgs;
allArgs[i] = args;
}
}
public function getArgs()
{
trace(this.allArgs[0][4])
}
}
}
I am going to use the getArgs function to return the values of the array, so I can use the XML info in other functions inside my document code.
This is a snippet of the code that calls the functions in the custom class:
Code:
xmlLoader.load(new URLRequest("data.xml"));
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(event:Event):void
{
var XMLInfo:XMLCache = new XMLCache(event.target.data);
XMLInfo.getArgs();
From what I understand this should return the entire array, but all Im getting is "Access of Undefined Property args @ return args;(in the custom Class)"
Any suggestions I could try would be much appreciated.
Thanks,
GC
Tween Class Not Recognizing Array Values [f8]
Hi. In AS2, I'm trying to use the tween class with an array, but it doesn't seem to be accepting the references. Here's the code:
code:
//Add Drive Mask
var NewDriveMaskInstance:MovieClip = this.attachMovie("drive mask", "mc_driveMask" + i, getNextHighestDepth());
NewDriveMaskInstance._x = aDMStartingX[i];
NewDriveMaskInstance._y = YValue;
//Animate the Drive Mask
trace(aDMStartingX[i]); // traces 980 correctly
trace(aDMEndingX[i]); // traces 910 correctly
trace(aDMYards[i]); // traces 7 correctly
var tempdrivemask:Object = new Tween(NewDriveMaskInstance, "_x", null, aDMStartingX[i], aDMEndingX[i], aDMYards[i], false);
NewDriveLineInstance.setMask(tempdrivemask);
It's the second to last line (the one beginning "var tempdrivemask:Object . . ." that's not working, specifically, the three references to array values just after the null.
I've tried assigning the values of the array references to temporary variables and referencing the temp variables instead, but that didn't work, either.
It does work if I just hard code the numbers into the tween, and it also works if I declare temporary variables and assign them hard values.
It does not work if I declare temporary variables and assign them values by referencing the array values
Any ideas? Any help would be greatly appreciated. Fairly new at this stuff.
Assigning Default Values For Class Properties
I am wondering about assigning default values for class properties. Is it as symbol as declaring the property and assigning a value:
public var my_property:type = value;
or is it better to declare a private property with the defualt value and then a public property with set to the default value:
private var defaultMy_property:type = value;
public var my_property:type = defaultMy_property;
Any thoughts would be great and thanks in advance.
Clear Stage And Clear Class Values?
I'm working with this tutorial to create a quiz, but modifying it to load the data from XML: Create a Quiz Application Using AS3 Classes
I would like to put a retry button at the end that would clear all previously set values and clear all the display objects that I've added to the stage and basically start the file over again as if it was the first time. Is this possible?
I would think there's an easy way since it is using external class files... I hope it doesn't require a lot of manual Remove Child At and clearing variable and array values.
Generating Random Values For A Variable While Excluding The Already Generated Values
Hey Flashers:
Here's my question this time around. I want to generate random values between 1and 50 for a variable but I want every time I generate the new value to exclude the already generated values from the pool of options. Something like playing the lottery where no two drawn numbers can be the same. Any hints or references to open code will be greatly appreciated.
As always, thanks a lot!
Function Populated By Node Values Returning Undefined Values
I have been working on some code which extracts the information from an xml document, styles it with css and then loads the various node values into a text field and arrays. The user click on a link in the text field which calls myFunction using asfunction and that in turn should enter the array values relating to that link into text fields.
Everything in general seems to work OK except the value that is returned to the two text fields on pressing the link in the CCTextField "which in turn calls myFunction" returns undefined for those values of the arrays. I check the agency[2] value in the function that populates the arrays and the value is returned as it shoiuld be so it appears there must be something amiss with myFunction, or at least it would seem so.
Any takers as to what this problem might be?
I have supplied some shortened code below.
PHP Code:
CCTextField.styleSheet = myStyle;
// NOTE: CCTextField styleSheet has been created beforehand
my_xml = new XML();
// NOTE: my_xml has been created beforehand
my_xml.onLoad = function(sucess) {
if (sucess) {
processXML(my_xml);
}
};
// Load up the XML file into Flash
my_xml.load('TEST.xml');
// This is the function that will be called when
// the XML document is loaded succesfully
function processXML(xmlDoc_xml) {
var listText_comm = ""; // List text variable
var entryNum = 0; // Entry number variable
var agency = new Array(); // Agency array
var production = new Array(); // Production array
for (var n = 0; n<xmlDoc_xml.firstChild.firstChild.childNodes.length; n++) {
categoryNodeName = xmlDoc_xml.firstChild.firstChild.childNodes[n].nodeName;
if (categoryNodeName == "client") {
listText_comm += "<a href='asfunction:_root.myFunction," + entryNum + "'>" + xmlDoc_xml.firstChild.firstChild.childNodes[n];
trace("client " + xmlDoc_xml.firstChild.firstChild.childNodes[n]);
} else {
if (categoryNodeName == "title") {
listText_comm += " - " + xmlDoc_xml.firstChild.firstChild.childNodes[n] + "</a>";
trace("title " +xmlDoc_xml.firstChild.firstChild.childNodes[n]);
} else {
if (categoryNodeName == "agency") {
agency[entryNum] = xmlDoc_xml.firstChild.firstChild.childNodes[n].firstChild.nodeValue;
trace("agency " +xmlDoc_xml.firstChild.firstChild.childNodes[n].firstChild.nodeValue);
} else {
if (categoryNodeName == "production") {
agency[entryNum] = xmlDoc_xml.firstChild.firstChild.childNodes[n].firstChild.nodeValue;
trace("production " +xmlDoc_xml.firstChild.firstChild.childNodes[n].firstChild.nodeValue);
entryNum++; // click over the entry number by 1
}
}
}
}
}
trace("AGENCY 2 = " + agency[2]); // this returns agency number 2 OK
_root.CCTextField.text = listText_comm; // CCTextField shows this text OK
}
function myFunction(listItem) {
clientF = agency[listItem]; // THIS RETURNS undefined ON PRESSING THE LINKS IN CCTextField
productionF = production[listItem]; // THIS ALSO RETURNS undefined ON PRESSING THE LINKS IN CCTextField
trace(listItem); // this trace = the list item passed by asfunction OK
}
[MX] Weirdness With Values Used By Array Populated Clip Values.
Hi,
I have used invisible buttons on top of some text, as part of a volume control interface.
The text buttons are set out as 0 – 25 – 50- 75 -100 referring to the % that a music tracks volume will change to once a button is pressed – so far so good.
Now to give values to the text buttons in order for them to make the text clip that they are on top of go to & stop & the right frame I have used arrays to give a reference the location of the text clip:
numbs_array = [_root.volHold_mc.vol0, _root.volHold_mc.vol25, _root.volHold_mc.vol50, _root.volHold_mc.vol75, _root.volHold_mc.vol100];
I then reference that in a home made “release” function as “this.monica.gotoAndStop(2);” “monica” being the reference to the address of the clip.
It all works fine except the code seems to make the movie play clips in an order that they have not been designated in the array – Like a button on top of the “25”% value will play the animation for the “75”% clip?
The whole problem is probably much better seen through the movie – the problem section of which i have attached below.
Passing Values From ASP To Change Alpha Values Etc
Is this possible? I currently have a log in system, logging each page a user visits, these visits amount to a value and have this value passed to flash to control alpha values, tints etc to reflect look and feel. is this possible?
Database Values To Array Values
Hi all,
I've created a movie which uses a number of arrays to construct the elements of a flash-based gallery.
What I need is a practical method of getting values from a database into an array via an ASP page.
The plan was to load the variables into these arrays using the an asp page and a loadvars object to create a string (basically the array values in quotes separated by commas) which was then to be inserted into the parameters for the creation of the array. Needless to say this hasn't worked- the create array object seems to interpret the whole string as the first value in the array, i can't find a way of populating the array from just a single asp page.
I've given up with this method and really need a few pointers.
Thanks
Writing Values To A Text File And Reading Values From The Same File
Hi, I want to create a page counter in Flash and I was wondering how to write a value (the next number for the visitor) to the text file and read the current value from that file. In a simplified form I would just read the number currently in the file, add 1, and rewrite the number to the file. Eventually when I get that worked out I will adapt it to only add 1 for each different user session instead of each page hit, but I'll start with the easy stuff first.
Thanks
Class Question: How To Access Timeline Objects From Class W/o Arguments
Hey all,
I am looking into builiding an application with OO functionality. I understand most of it. Except I cannot figure out how to access something in my app from a class. For instance, lets say I have one Loader class that loads some data and stores it in a variable inside the class (or on the main timeline, doesn't matter). Now, I know I can pass a reference to the data in an argument to another class for that class to manipulate. But if I have several data sources, and other variables and such, that I need to modify in a single class function, how would I do that without having to give the function access to them through arguments? I just want to be able to say, from a class, something like _root.someObject.someFunction();
So, any help would be greatly appreciated, and sorry if that made no sense at all, I tried to explain as best I could.
Happy Holidays!
Dave
[Flash 8] Referencing Class Variables From OnEnterFrame Created Within Class
Hi,
It's been a while since my last post here, but I was hoping someone could help me with a problem I'm having. I want to reference and change a class variable from within an onEnterframe function defined within a class. I can actually do this right now, but I want to do it in a different way. Here's a code sample of what I am talking about:
Test.fla file:
Code:
var t:tester = new tester()
Working tester.as file:
Code:
class tester{
private var num:Number = 100;
function tester(){
var classObj:tester = this;
var mc:MovieClip = _root.createEmptyMovieClip("test",1);
mc.onEnterFrame = function(){
trace(classObj.num); //This traces 100 (CORRECT!!!)
}
}
}
This traces 100 to the output window, just like it should
Here is the way that I would like to do it, because I want to reuse my onEnterFrame Stuff:
Code:
class tester{
private var num:Number = 100;
function tester(){
var classObj:tester = this;
var mc:MovieClip = _root.createEmptyMovieClip("test",1);
mc.onEnterFrame = this.mcOnEnterFrame;
}
private function mcOnEnterFrame(){
trace(num) //this traces undefined (BAD!!!)
}
}
As you can see, the work around to reading the class variable in the onEnterFrame function is to create a reference to the class object, before defining that function, then using the reference you created to access the class variables.
I have tried various iterations to get the second example working, but have had no luck. Does anyone know a way to get the second method working, or am I stuck using the first method.
AS3 Project In FDT + Flex SDK. Root Class Extends Visual Class From Swc
hello
question about compiling as3 project under FDT 3.0 with Flex SDK.
I want my main root class to contain some graphics already at the start. In Flash IDE I put some objects on the stage, make new symbol with all those objects inside, set linkage to MainClassGraphics, export it to swc, add this swc to source folder class-path. Then I write my root class:
Code:
package {
public class MainClass extends MainClassGraphics {
public function MainClass() {
trace('hey');
}
}
}
compiling with flex2 sdk - and I don't see any graphics. why?
if i try this way:
Code:
package {
import flash.display.Sprite;
public class MainClass extends Sprite {
public function MainClass() {
var s:Sprite = new MainClassGraphics();
addChild(s);
trace('hey');
}
}
}
then I see my graphics.. so swc looks like fine
crosspost here http://fdt.powerflasher.com/forum/vi...hp?f=21&t=2268
Accessing A Dynamic Text Field In A Class Other Than The Primary Class
I have tried to read and understand some of the other threads for this issue but, I think it would be easier to understand if I show my specific issue. I left some code out to make my issue more clear.
Alpha is the primary class with access to the stage. If I write the event listener and function contained in the Bravo function into the Alpha function it works. Although, I want it to be in a different class in the same package (such as the Bravo class).
I have created a instance of a class which is a physical object on the stage (lets say it's a card). The event listener is in the instance so that each instance has a self contained listener.
The bottom line is it works in the primary class but in no others. How can I make it access the text field (so when I click on the "card" the text field shows "something"?
ActionScript Code:
package a {
public class Alpha {
public function Alpha() {
x:Bravo = new Bravo();
}
}
}
package a {
public class Bravo {
public function Bravo() {
this.addEventListener(MouseEvent:CLICK, clickEvt);
function clickEvt(event:MouseEvent) {
<MovieClip>.<MovieClip>.<DynamicTextField>.text = "something";
}
}
}
}
Calling SetTimeout Within Custom Class And Cannot Access The Class' Variables
Hi All,
I'm creating an user interface with Flash 8, I'm new to Flash, my background is Java therefore I decided to use ActionScript to create a custom component that is reference within an external file.
My problem I believe is scope related. I have a status bar (label component), once I update the status bar I want to call the
"setTimeout" function to wait a couple of seconds before clearing my status bar. The "setTimeout" function is executing, but for some reason my status bar is not being cleared (accessed).
Below is a snippet of my code. Any help appreciated. Thanks.
/*
External File
*/
import mx.controls.Button;
import mx.controls.Label;
class MyApp
{
//private properties
private var mc_container:MovieClip;
private var btn:Button;
private var lbl_status:Label;
private var str:String = "do see me";
//constructor
public function MyApp(target:MovieClip)
{
trace("-- MyApp --");
mc_container = target.createEmptyMovieClip("mc_container", 100);
}
//public methods
public function init(width:Number, height: Number, xPos:Number, yPos:Number):Void
{
var my_app:MyApp = this;
btn = mc_container.createClassObject(Button, "btn", 1, {label:"click me"});
btn.setSize(100, 25);
btn.move(10, 10);
btn.clickHandler = function():Void
{
trace("btn clicked");
setTimeout(my_app.clearStatus, 2400);
//correct if I call directly
//my_app.clearStatus();
trace(str);
}
lbl_status = mc_container.createClassObject(Label, "lbl_status", 2, {text:"status bar message"});
lbl_status.setSize(200, 25);
lbl_status.move(0, 50);
}
public function clearStatus():Void
{
trace("calling clearStatus");
lbl_status.text = "";
}
}
/*
Called for Flash IDE
*/
var app:MyApp = new MyApp(this);
app.init(200, 200, 0, 0);
ActionScript 2.0 Class Scripts May Only Define Class Or Interface Constructs.
This is driving me nuts. I have an old AS1 project which I upgraded to AS2. It uses an include file, settings.as, which has stuff like this:
settings = new Object();
settings.property = 'some value';
Then I include it on the main timeline like this:
#include "settings.as"
Every time I render, I get a million and one Compile Errors stating:
"ActionScript 2.0 class scripts may only define class or interface constructs."
But it isn't an ActionScript 2.0 class! It's just a regular include. How do I avoid the bogus Compile Errors?
AddChild Works With Document Class, But Not Timeline-instantiated Class
I cannot get a sprite to display for me when I create an instance of a very simple class in my FLA file's timeline.
However, when I make the class file the FLA's document class file, it displays just fine.
The task in question is simply drawing a square with the shape class.
Problem example:
My class, Test.as, resides in the same folder as my FLA file - so I don't use any import statement. I'm new to lots of CS3 stuff. Can anyone tell me why this doesn't work and create the shape on the stage? This seems to fail silently without any errors:
var myTest:Test = new Test();
Working example:
Setting the document class to Test.
Attach Code
// Test class
package {
import flash.display.*;
public class Test extends Sprite {
public function Test():void{
doThing();
}
private function doThing():void{
var myRect:Shape = new Shape();
myRect.graphics.lineStyle (2, 0xcc0000, 1);
myRect.graphics.beginFill(0xcccccc, 1);
myRect.graphics.drawRect(10, 10, 200, 200);
addChild(myRect);
}
}
}
[AS3] Making An Auto-generated Class Inherit From Custom Class?
hi, just wondering if this is possible
i was hoping to find a way to get a bunch of objects in my library to inherit from (or even be) one class that i have made, but without having to make .as files for every single one
is this possible, or is there any other way to give objects another classes functionality in an auto-generated class?
cheers
Tough One: Accessing Class Methodes From Other Class Files
Tough question for the experts...
In my classfile class Classes.tools.depthManager, I've got a static methode
Code:
public static function getLoopDepth():Number {
In another classfile Classes.tools.frameRateViewer, I want to access that methode
Code:
var tempDepth = Classes.tools.depthManager.getLoopDepth();
The compiler claims: "There is no class or package with the name 'Classes.tools.depthManager' found in package 'Classes.tools'."
So I tried writing import Classes.tools.* at the top of my Classes.tools.frameRateViewer.as, hoping I could just write
Code:
var tempDepth =depthManager.getLoopDepth();
But there the compiler claims: "The class being compiled, 'Classes.tools.depthManager', does not match the class that was imported, 'depthManager'."
I'm sure the Classes.tools.depthManager.as works fine: I can call the static depthManager.getLoopDepth() from a button in the fla file...
Any ideas? Thanks!
Button Created Within Class Cannot Access Class Properties
Hi,
I'm using the following code within a class:
code:
_head_mc.attachMovie("headButton", "head_btn", this.getNextHighestDepth());
_head_mc.head_btn.onRelease = function () {
containingClip_mc._parent._parent.clickedHead(_per sonName);
}
The button gets attached (line 1). This works because I can see the mouse changing to a finger.
The onRelease function is declared and works. I know because if I put a trace in there, it works.
The function it calls (containingClip_mc._parent._parent.clickedHead also works, becuase I can see traces from within it.
But the _personName variable is passed as undefined.
I know that this variable has a value, because I can trace it outside the function, but it seems that this onRelease function is not able to see the variable. It's declared as private, but setting it to public doesn't fix anything.
I imagine there's something I don't understand about the scoping of variables. I've tried _parent references, but that doesn't appear to help either. Is there a better way to do this or a workaround?
Barrette
Added by edit
Okay, I've pretty much determined this is a scoping issue. From the onRelease function, I'm unable to access ANY of the functions within my class. I still would like advice on how to do so..
Barrette
**Error** ActionScript 2.0 Class Scripts May Only Define Class........
**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b2.onPress = function() {
**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b3.onPress = function() {
**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b4.onPress = function() {
ok this is what i have.
1 Movie clip with links to a .as file all is working fine the above error occurs when i publish the 1 movie clip which is getting pulled into the main movie
Any idea's it does not happen when 1 movie clip is published on its own just when 1 move clip is pulled into my main movie clip.
[F8] Referencing A Static Class Inside Another Class's Instance
I've got a movie loading into a framework.
This framework has 1 instance of the class main called main.
Inside this class, another class is used, but it is used directly, not as an instance. E.g.:
code:
import com.StaticClass;
class main {
private function UseStaticClass():void {
StaticClass.init();
}
}
From my movie, I can reference the main instance as _root.main. Can I reference StaticClass at all if there's no explicit instance created or it's not assigned to a public variable?
I can't modify main to include getter/setter methods, that's why I ask.
Thanks.
Child Class Trigger Event For Parent Class
is there a way for a parent class to listen to a variable in a subclass, and when it changes, run a function?
This seems like a pretty simple thing to do. I'm trying to keep my subclass independent of my main class, so i just have a variable that is set to false, and when its finished, it sets the variable to true.
The only thing i can think of is having an onEnterFrame that keeps checking the variable...but it seems like an event would be more efficient.
thanks!
Tween Class Applied In Custom Class Not Working
var sizerW:Object = new Tween(pda_mc,"_xscale",mx.transitions.Tween.None.e aseNone,pdaOrigW,pdaSmallW,3,true);
this code produces and error when applied in a custom class but not in a fla?
the error = There is no property with the name 'None'.
Custom Transitionmanager Class Problem/class Scope?
I'm writing a class that fades from one scene to another in a video game. A custom transitionManager object is created, and a listener is attached. Once the fade out from one scene is complete, the listener is triggered, the scene switches, and the new scene fades in.
This is the error I'm getting: "There is no method with the name 'myTransitionManager'.
myTransitionManager.addEventListener("allTransitio nsOutDone", fadeListener);". It is given everytime myTransitionManager is accessed by any of the class functions.
I assume this is a class scope issue. How can I create a custom transitionManager object accessable to the entire class? I need it to be accessed by at least three separate class functions.
Here's the source, starting with the constructor for the GameSection class:
Code:
public function GameSection(clip_to_fade:MovieClip){
var myTransitionManager:TransitionManager = new TransitionManager();
}
//class methods
function switch_section(clip_to_fade:MovieClip, fade_in_scene:String) {
// Define a listener object to use with the Tween objects.
var fadeListener:Object = new Object();
//create event listener for transitions being complete
fadeListener.allTransitionsOutDone = function(eventObj:Object) {
trace("allTransitionsOutDone event occurred.");
gotoAndPlay(fade_in_scene);
fadeIn(clip_to_fade);
};
myTransitionManager.addEventListener("allTransitionsOutDone", fadeListener);
fadeOut(clip_to_fade);
}
function fadeIn(in_mc:MovieClip) {
myTransitionManager.start(in_mc, {type:Fade, direction:Transition.IN, duration:1, easing:None.easeNone});
}
function fadeOut(out_mc:MovieClip) {
myTransitionManager.start(out_mc, {type:Fade, direction:Transition.OUT, duration:1, easing:None.easeNone});
}
Thanks!
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?
Why Is An Event On One Class Object Being Broadcast For All Instances Of That Class?
I have a custom class called McText which extends MovieClip, and includes an input text field. That class has a function to register itself as a listener to Key - Key.addListener(this). It does not register by default.
There are multiple instances of McText. But even though I only call the function to register on one of those instances, ALL of them fire an onKeyDown function when i type into their text field, regardless of whether i've registered that particular object to Key or not. I register one, I register them all.
This is a little annoying because I use this class everywhere, and I want to be able to assign an onKeyDown function for only one of them. At first i tried writing that function outside of the class itself, as in:
classObject.onKeyDown = function()
But that, perhaps unsurprisingly, created an onKeyDown function for every instance again.
I thought to myself "I know, I'll register McText with Key by default (in the constructor), write an McText.onKeyDown function in the class itself, and then get that function to use a broadcaster". The idea being that onKeyDown will fire on all of them, but the broadcaster will be registered to a specific listener on an object by object basis.
So I did that, and created a function to register a broadcaster listener. I then created a broadcaster listener in a seperate, different, class, throw it to the McText function so it registers with its broadcaster and guess what? Now that listener receives an event from every instance of that class.
There's no explicit use of static vars or functions anywhere.
Sorry for the long question, but can anyone enlighten me as to what's going on? You get virtual chocolate if you do
How Do You Listen In One Class For A Custom Event Dispatched From Another Class?
I am not sure how to word this, so here is what I would like to happen:
MyDocumentClass contains an instance of MyItem and MyItemManager. MyItem will fire an ItemEvent.ITEM_CHANGED event. I want MyItemManager to listen and react to that event. Possible? Here's my code:
ItemEvent.as:
ActionScript Code:
package
{
import flash.events.Event;
public class ItemEvent extends Event
{
public static const ITEM_EVENT:String = "itemEvent";
public function ItemEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
super(type, true);
}
public override function clone():Event
{
return new ItemEvent(type);
}
public override function toString():String
{
return formatToString("ItemEvent", "type", "bubbles", "cancelable");
}
}
}
MyDocumentClass.as:
ActionScript Code:
package {
import flash.display.Sprite;
import MyItem;
import MyItemManager;
public class MyDocumentClass extends Sprite
{
public var item:MyItem;
public var manager:MyItemManager;
public function MyDocumentClass()
{
item = new MyItem();
manager = new MyItemManager();
item.dispatchCustomEvent();
}
}
}
MyItem.as:
ActionScript Code:
package
{
import flash.display.Sprite;
import flash.events.EventDispatcher;
import ItemEvent;
public class MyItem extends Sprite
{
public function MyItem()
{
}
public function dispatchCustomEvent():void
{
dispatchEvent(new ItemEvent(ItemEvent.ITEM_EVENT));
}
}
}
MyItemManager.as:
ActionScript Code:
package
{
import flash.display.Sprite;
import ItemEvent;
import flash.events.EventDispatcher;
public class MyItemManager extends Sprite
{
public function MyItemManager()
{
addEventListener(ItemEvent.ITEM_EVENT, handleItemEvent);
}
public function handleItemEvent(e:ItemEvent):void
{
// do something here
}
}
}
Document Class Initialising Another Class With Display Objects
Hi
I'm currently learning AS3 and have got stuck with something fundamental to do with Flash and the Document Class.
I have a very simple Document Class as follows:
package {
import flash.display.*;
import com.Application;
public class EntryPoint extends Sprite {
public function EntryPoint() {
var app:Application = new Application();}}
}
I then would like to build out into other classes/patterns and want the following code to simply attach an item from the library on to the stage.
The item in the library has a Class reference of CircleTest and has a Base Class of flash.display.Sprite.
My Application class is as follows:
package com {
import flash.display.*;
public class Application extends Sprite{
public function Application() {
var mc_root:Sprite = new Sprite();
addChild(mc_root);
var circleTest:CircleTest = new CircleTest();
mc_root.addChild(circleTest);}}
}
When I compile this from Flash I get nothing other than an empty stage :-(
Please can someone tell me what I'm doing wrong here.
Many thanks in advance
D
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
Applying A Custom Class To An Object In The Document Class...
How's it going guys. I just started learning Actionscript 3.0 and so far not bad. However, I'm having trouble applying custom created classes to objects in the main document class. I'm using Flash as the application, however there is no timeline scripting involved. I loaded the document class called Main.as:
ActionScript Code:
package
{
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.display.Loader;
public class Main extends MovieClip
{
private var _redBox:Loader = new Loader();
private var _redBoxLink:URLRequest = new URLRequest("images/redbox.jpg");
public var buttonScaleHover:ButtonScaleHover = new ButtonScaleHover();
public function Main()
{
_redBox.x = 100;
_redBox.y = 100;
_redBox.load(_redBoxLink);
addChild(_redBox);
}
}
}
Now, what I'm trying to do is apply this class named ButtonScaleHover.as to the _redBox in the document class. Here is the code for ButtonScaleHover:
ActionScript Code:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class ButtonScaleHover extends Sprite
{
private var _xScale:Number;
private var _yScale:Number;
public function ButtonScaleHover()
{
trace("The ButtonScaleHover Class is being loaded");
_xScale = this.scaleX
_yScale = this.scaleY
this.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
this.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
}
public function onRollOver(event:MouseEvent):void
{
this.scaleX *= 2;
this.scaleY *= 2;
}
private function onRollOut(event:MouseEvent):void
{
this.scaleX = _xScale;
this.scaleY = _yScale;
}
}
}
I tried using
ActionScript Code:
_redBox.ButtonScaleHover();
in the document class after i added it to the display object list. However, it didn't work. Basically, I'm just trying to apply a custom class to an object(in this case the loader). Thank you guys very much in advance.
Call Function Of Document Class From MovieClip Class
How can I run a function of the main document class from a class of a MovieClip? I usually just used MovieClip(parent).function(), but now my MovieClip has another parent. Or what do I have to pass to the MovieClip class when creating the MovieClip to acess the main document class?
Sharing Vars Between Document Class And An Imported Class.
I'm working on my first really in depth AS3 project, learning as I go.
I've been sorting through the XML docs and i've bumped my head into a bit of a question. So, to preface, I have been able to load the XML successfully, but I want to be able to use my own XML loader class to load the XML and then be able to reference it from the document class. Also, I'd like to be able to send a file path to the loader class when I call it.
Not sure if that makes sense, but I will post what I did and see how bad it is
The document class:
ActionScript Code:
package rg.sites{
// flash classes
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.*;
import flash.display.Graphics;
import flash.display.Shape;
import flash.text.*;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.net.*;
import flash.errors.*;
// RG classes
import rg.classes.XMLSiteLoader;
// Layout Objects
public class SiteCurrent extends MovieClip {
// vars
public var siteLoader:XMLSiteLoader;
public var site_xml:XML;
public var xml_site_loading:String = "current_site.xml";
public function SiteCurrent() {
trace("Site Current is loaded");
siteLoader = new XMLSiteLoader();
siteLoader.addEventListener(Event.COMPLETE, xmlSiteLoaded);
}//end constructor function
private function xmlSiteLoaded(event:Event):void {
trace(site_xml.toXMLString());
trace("
" + "Background art: " + site_xml.section.(@id == "Splash"));
}
}//end class
}//end package
The XMLSiteLoader class:
ActionScript Code:
package rg.classes
//
// XMLSiteLoader version 0.1 beta
//
{
//import fl.controls.*;
import flash.net.*;
import flash.events.*;
import flash.errors.*;
public class XMLSiteLoader extends EventDispatcher {
//public var site_xml:XML;
private var siteReq:URLRequest;
private var siteLoader:URLLoader = new URLLoader();
public var site_xml:XML;
public var xml_to_load:String;
public function XMLSiteLoader() {
//trace(stage.xml_site_loading);
if(xml_to_load == true) {
trace("xml file path sent");
siteReq = new URLRequest(xml_to_load);
}
else {
trace("No XML file path sent, use default value");
siteReq = new URLRequest("current_site.xml");
}
trace("XML Site Loader is loading: " + siteReq);
siteLoader.load(siteReq);
siteLoader.addEventListener(Event.COMPLETE, xmlLoaded);
} // constructor class
private function xmlLoaded(event:Event):void {
site_xml = new XML(siteLoader.data);
trace("
" + "from XML Site Loader: " + site_xml.section.(@id == "Splash"));
dispatchEvent(new Event(Event.COMPLETE));
}
}//end class
}//end package
I get an error that says:
Quote:
Site Current is loaded
No XML file path sent, use default value
XML Site Loader is loading: [object URLRequest]
from XML Site Loader: portfolios/splash_gallery/splash.xml
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at rg.sites::SiteCurrent/xmlSiteLoaded()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at rg.classes::XMLSiteLoader/xmlLoaded()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
Thanks in advance for any thoughts or suggestions.
-g
Displaying A TextField From A Class That Is Called From My Document Class
I'm having a problem with my main project so I've made a small test project to replicate it. The code's included here.
I've created a new .fla called TextboxFromClass.fla that's empty except for a linked in Document class called TextboxFromClass.as
I've created another class called TextboxClass.as
Everything's linked and referenced properly - when I run it there's no errors and I get a trace output "Got here" but only the TextField for the Document Class displays ("From the Doc Class"), not the one from the TextboxClass ("From the TextBoxClass Class").
I'm guessing it's a scope thing but I'm fairly new to ActionScript 3.0 so I'd appreciate your help.
Attach Code
//Code in the Document Class (called TextboxFromClass.as
package script
{
import script.*
import flash.display.MovieClip;
import flash.text.*;
public class TextboxFromClass extends MovieClip
{
var inputNameLabel:TextField = new TextField();
var backgroundGreen : int = 0x2E510B;
var foregroundGreen : int = 0x00FF99;
public function TextboxFromClass()
{
with (inputNameLabel)
{
x = 300;
y = 200;
width = 200;
height = 30;
text = "From the Doc Class";
}
var format:TextFormat = new TextFormat();
with (format)
{
font = "Arial";
color = foregroundGreen;
size = 20;
}
inputNameLabel.setTextFormat(format);
addChild(inputNameLabel);
//This should output some text like the above - but doesn't
var abc:TextboxClass = new TextboxClass();
}
}
}
// Code in TextboxClass.as
package script{
import script.*;
import flash.display.MovieClip;
import flash.text.*;
public class TextboxClass extends MovieClip {
var t:TextField = new TextField();
var backgroundGreen : int = 0x2E510B;
var foregroundGreen : int = 0x00FF99;
public function TextboxClass() {
with (t) {
x = 300;
y = 250;
width = 300;
height = 30;
text = "From the TextBoxClass Class";
}
var format:TextFormat = new TextFormat();
with (format) {
font = "Arial";
color = foregroundGreen;
size = 20;
}
t.setTextFormat(format);
addChild(t);
trace("Got here");
}
}
}
Edited: 02/09/2008 at 07:42:24 AM by SoCentral2
Tween Class In Custom Extend MovieClip Class
I want to use the tween prototype in a custom class that extends MovieClip. I am already including "lmc_tween.as" in my root and I have already replaced the "MovieClip.as" file in my flash directory with the one from the shared/Zigo directory. However, I still get compiler errors if I try to include "lmc_tween.as" in the class file, or without the include in the class it will compile but the tween prototype will not work in the custom class. Does anyone know how to fix this?
Checking To See If One Instance Of Class Hits Other Instances Of The Same Class?
Hi guys, the idea is similar to Yugop.com JAMPACK 01.
Let's say i have a bunch of balls/cells. I'm having trouble figuring out how to make it so that every other ball bounces off of every other ball.
so in short, it's really one instance being able to check all other instances of the same ball class?
any ideas guys and if you dont know what im talking about, please feel free to state that also.
Instantiating Character Class Inside Of Game Class
I am having a problem instantiating a Character class inside of a game class.
P.S. I am working on converting http://oos.moxiecode.com/tut_01/index.html these tutorials to A.S. 2.0.
Game:
ActionScript Code:
if ( i == charPos[1] && j == charPos[0] ) {
var char:Character = new Character();
char._x = (j*tileWidth)+tileWidth/2;
char._y = (i*tileHeight)+tileHeight/2;
}
Character:
ActionScript Code:
class classes.Character extends MovieClip {
function Character() {
var h = createEmptyMovieClip("holder", getNextHighestDepth());
var char = h.attachMovieClip("char", "char", getNextHighestDepth());
trace("new character created");
}
}
Applying A Custom Class To An Object In The Document Class...
How's it going guys. I just started learning Actionscript 3.0 and so far not bad. However, I'm having trouble applying custom created classes to objects in the main document class. I'm using Flash as the application, however there is no timeline scripting involved. I loaded the document class called Main.as:
package
{
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.display.Loader;
public class Main extends MovieClip
{
private var _redBox:Loader = new Loader();
private var _redBoxLink:URLRequest = new URLRequest("images/redbox.jpg");
public var buttonScaleHover:ButtonScaleHover = new ButtonScaleHover();
public function Main()
{
_redBox.x = 100;
_redBox.y = 100;
_redBox.load(_redBoxLink);
addChild(_redBox);
}
}
}
Now, what I'm trying to do is apply this class named ButtonScaleHover.as to the _redBox in the document class. Here is the code for ButtonScaleHover:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class ButtonScaleHover extends Sprite
{
private var _xScale:Number;
private var _yScale:Number;
public function ButtonScaleHover()
{
trace("The ButtonScaleHover Class is being loaded");
_xScale = this.scaleX
_yScale = this.scaleY
this.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
this.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
}
public function onRollOver(event:MouseEvent):void
{
this.scaleX *= 2;
this.scaleY *= 2;
}
private function onRollOut(event:MouseEvent):void
{
this.scaleX = _xScale;
this.scaleY = _yScale;
}
}
}
I tried using
_redBox.ButtonScaleHover();in the document class after i added it to the display object list. However, it didn't work. Basically, I'm just trying to apply a custom class to an object(in this case the loader). Thank you guys very much in advance.
Import Entire Class Directory Vs Specific Class
First off i've already tried searching for the answer with no luck.
Is there any benefit to only importing the specific classes you need as opposed to importing the entire class directory?
Example:
import flash.display.Loader;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.display.Sprite;
import flash.display.BlendMode;
import flash.display.Bitmap;
import flash.display.BitmapData;
etc.....
vs
import flash.display.*;
Id like to clean up my code but not at the expense of performance....or does this just increase compile time?
|