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




2 Class Instance With Members Pointing To The Same Place...?



I'm using Flash MX 2004 Professional and this loks like a bug to me...

Here's the problem, i'm making a game and something strange is going on. I found out that when I create a new instance of a class, it comes with the data from the last one created. These are my classes...

class SquadManager - This class controls all the alien squads, I have just one instance. It has an array of squads:
var Squads:Array = new Array();

class Squad - This is the actual squad of aliens. it controls all its aliens, check if they are alive and give a power-up when they all die. It has an array of aliens:
var Aliens:Array = new Array(0);

class Alien extends MovieClip - This is an Alien. Here i do collision test, move it, etc.

Inside the SquadManager, I create random squads with this function:

public function spawn(type:String, x:Number, y:Number) {
var name = "squad_" + SquadCounter++;
var newSquad:Squad = new Squad(name,type,int(x),int(y));
Squads.push(newSquad);
}

And here's the funny part...
Every time I make a new isntance of Squad (the newSquad above), if I check the contents of the Aliens array in this new Squad, it contains all the previously created aliens of the last new squad.
And more... The Aliens array in all my Squads point to the SAME array. If I add or remove an element in one instance's Aliens, all the other ones are affected the same way, as they were pointing to the same array.

Because of this, all the aliens are speeding up when another squad is spawned, because I move them twice when I loop thropugh the squads.

I'm pretty sure there's no flaw here, in the Squad constructor, I print all its properties are they are undefined, but the Aliens array is being shared with all other Squads...

Please someone give me some light...

This is my game as it is now



FlashKit > Flash Help > Flash ActionScript
Posted on: 11-09-2003, 09:36 PM


View Complete Forum Thread with Replies

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

AS2 Vs. AS3: Pointing To An Instance?
Hi,

In AS2 it's possibly to point to an instance dynamically this way:


Code:
for (var i:Number = 0; i<=3; i++) {
var mc:MovieClip = this["ball"+i+"_mc"].dot_mc.border_mc;
mc._visible = false;
}
How to do the same in AS3?

Class Members
What security is provided by the private variables in flash. I know it provides encapsulation, but how exactly. When a user uses a class, that means he has the class .as file. He can simply open it up and see the code. When we load a movie clip that uses a class into another movieclip, the parent movie clip can access the private variables of the class used in child movieclip. For components, yes they are useful, but what i wanted is a scenario (other than components) where private variables provide security to our code in the class.

Moreover I can access private variables if i dont use strict data typing. Use can also access private variables if u've imported a class in first frame and try and access its private variables in another frame. A person (not the author)can use any of these things to gain access to private variables. Please help me in understanding the concept of private variables.

[CS3] OOP: MCs And Buttons As Class Members
I've been working on a signage project for our new office building that will let users see floor plans and tell who is in which office and what their Gtalk status is. So far I've got a working concept (test movie) but as you can see, it doesn't load all the statuses at the start. It's working off of one LoadVars object and the script executes too fast for the variables to be loaded for the other offices. However, the problem is corrected when an individual office is rolled over.

My intention is to create an object called office that will hold a background MC (the part that changes color), a button (the part that initiates actions), an offices number string, and a LoadVars for each office. Ideally I'd like to be able to instantiate the offices once and then just have the code in the class definition handle the actions so I don't have to define actions for every single office (code for 100 buttons? I don't think so...).

Here's what I have so far (working with Action Script 2.0):

Code:
class office{
var officeNumber:String;
var backgroundMC:MovieClip;
var officeButton:Button;
var officeLoadVars:LoadVars;

function office(n,mc,button,dx,dy){
officeNumber = n;
backgroundMC = mc;
officeButton = button;

//initialize positioning
backgroundMC._x = dx;
backgroundMC._y = dy;
officeButton._x = dx;
officeButton._y = dy;

//set the displayed office number
backgroundMC.number.text = officeNumber;

setStatus();
}

offcVars.onData = function(success){
if(success){
//process the data and put it in the tooltip window
// exe- tooltip.name.text = officeLoadVars.name
// tooltip.message.text = officeLoadVars.message
}
}

function changeBGColor(code){
//change the bg color of the office bgMC
//either use setTranform or change the _currentframe
}

function setOfficeStatus(){
//php file takes an office number and returns:
//Occupant name or use (person vs storage vs training room)
//Gtalk status (already externally coded for; available, busy, idle, ect.)
// Gtalk status message (exe- Out to lunch; Working from Home)
officeLoadVars.load("getOfficeStatus.php?room="+officeNumber);
changeBGColor(officeLoadVars.statusCode);
}

officeButton.onRollOver = function(){
revealToolTip();
setOfficeStatus();
}

officeButton.onRelease = function(){
revealToolTip();
setOfficeStatus();
}

officeButton.onRollOut = function(){
hideToolTip();
}
}
The idea is to pass in a movie clip and a button already on the stage and have the actions inside the class handle everything that I was typing out manually before. The problem is I'm getting stuck at errors for the button functions I'm trying to define.

Is it even possible to do what I'm attempting? (If something doesn't make sense, PLEASE let me know).

Access To Class Members In OnLoadInit?
Hi

I'm trying to throw together an image loader class for reuse. Everything seems to work except for one thing: once the image is loaded, I can't set the loaded image's position or size. I want to set the _x, _y, _width, & _height properties in onLoadInit from the containing class' members, but inside my event handler, those members are considered "undefined". I'm sure this has come up in this forum before, but I couldn't find a thread specific to this problem. My code is below.

- O8

in VideoImage.as


Code:
class VideoImage
{
private var mContainer : MovieClip;
private var mX : Number;
private var mY : Number;
private var mWidth : Number;
private var mHeight : Number;
private var mSourceUrl : String;
private var mLoader : MovieClipLoader;
private var mListener : Object;

public function VideoImage( pContainer : MovieClip,
pX : Number,
pY : Number,
pWidth : Number,
pHeight : Number,
pSourceUrl : String )
{
mContainer = pContainer;
mX = pX;
mY = pY;
mWidth = pWidth;
mHeight = pHeight;
mSourceUrl = pSourceUrl;

LoadImage();
}

private function LoadImage() : Void
{
mContainer.createEmptyMovieClip( "mcVideoImage", mContainer.getNextHighestDepth() );
mLoader = new MovieClipLoader();
mListener = new Object();
mListener.onLoadInit = function( image : MovieClip )
{
image._x = mX;
image._y = mY;
image._width = mWidth;
image._height = mHeight;
}
mLoader.addListener( mListener );
mLoader.loadClip( mSourceUrl, mContainer.mcVideoImage );

return;
}
}

in the fla on frame 1


Code:
var image:VideoImage = new VideoImage( this, 0, 0, 60, 70, "http://northport.k12.ny.us/~enms/ahern/budda2/orionpic.jpg" );

Why Doesn't My XMLObject Reference Other Members Of The Class?
Why doesn't checkXML ever run? How can I run it when the XML loads? This code with minor adjustemts works in fla file if I put it on a frame. What gives? That seems crappy.


Code:
class Thumbnail extends MovieClip {
static var tWidth:Number;
static var tHeight:Number;
static var maskName:String;
var xmlFile:String;
var xmlObj:XML;
var error:String;

function Thumbnail() {
if(!tHeight) {
tHeight = 50;
}
if (!tWidth) {
tWidth = 100;
}
this.xmlFile = "xmlPhotoData.xml";
this.xmlObj = new XML();

this.xmlObj.ignoreWhite = true;
this.xmlObj.onLoad = function(success:Boolean) {
if (!success) {
error = "XML Data could not be loaded";
} else {
checkXML();

}
}
this.xmlObj.load(this.xmlFile);
if(this.error) {
trace("Error in Thumbnail class:");
trace(" "+this.error);
}
}
function checkXML() {
trace("CheckXML never runs");
for (var i=0; i<this.xmlObj.firstChild.childNodes.length; i++) {
trace(this.xmlObj.firstChild.childNodes[i].childNodes[0].firstChild.nodeValue);
trace(this.xmlObj.firstChild.childNodes[i].childNodes[1].firstChild.nodeValue);
}

}

}

Class Members Memory/performance Considerations?
I'm developing a half-decently large flash application, and I have a good dozen geometry-related classes. Most of them have about 6 levels of inheritance (down to Object level)

These classes have several methods and properties averaging about 400 lines of code each.

During the course of the application, hundreds and possibly thousands, of these objects are created. I'm wondering if the methods are duplicated for each object in memory or if they're statically stored and don't take up extra memory.

I seem to remember something about using Prototypes and that they are re-used for all instances of that class so it doesn't take up extra resources. Is that the same case for AS2 classes? Or should I refactor my classes so that they only contain variable properties and I use static helper methods to alter them?

Custom Class Object Exposing Private Members
HI

I have a custom class (Player) that is created to hold data about a player - name, score etc and it also performs some other tasks worthy of making it into its own class.

So that I can persist data on the client machine I am trying to store a Player instance in an array of players on a local SharedObject.data.players_ar Array.

I have no problems adding a new player to the array of players on the SharedObject - but when I do this, I find that I am able to access private properties of the Player instance that would under normal cirmcumstances not be avaiable through an instance of the Player class. In fact accessing them throws an error - as I would expect.

So can anyone explain why - one an instance of the Player class has been attached to a ShareObject that not only are private class properties exposed, but that the getter and setter methods of that instance also stop working?

Thanks in advance

Place An Instance Randomly On Screen
how can i place a number of instances of a graphic randomly over the screen, with diffrent sizes and alpha

Function To Place An Instance Of Any Symbol In The Library
I'm trying to create a function that will allow me to place any symbol in the library on the stage. I'm getting hung up on the second line of the function. I am not having a problem with the script to place a specific instance on the stage, but I want to be able to pass the symbol, and the destination coordinates to the symbol. I'm quite new, and I know there is something I am not understanding about instantiating an object.

function PlaceSymbolFromLibrary(getSymbolClass,position_x,p osition_y) {
var NewSymbolInstance:getSymbolClass = new doingSomethingWrongInThisLine;
NewSymbolInstance.x = (position_x);
NewSymbolInstance.y = (position_y);
addChild(NewSymbolInstance);
}
function PlaceGroupOfSymbols() {
PlaceSymbolFromLibrary(mySymbol,100,100);
}

PlaceGroupOfSymbols();

Any help would be very much appreciated

[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.

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?

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.

Returning The Instance Name Of A Class From Within The Instance
Hi,
I'm trying to do some error reporting in my actionscript.
I have a class MyData which can be instantiated several times over in each project e.g.
var myData1:MyData = new MyData();
var myData2:MyData = new MyData();

In the error reporting I have put statements like
trace("MyData.loadData reports error.... message...");

However, I'd really like it to return the instantiated name, not the generic class name so that I can trace errors to the particular instance that is failing. Does anyone know how to do this? I've tried
trace(this.toString() + " reports error.... message...");
but I just get a name of [object object] which isn't that helpful!

Many thanks!

Delete Instance Of Class From Class' Method
So I have a class called Unit. When I use this class in a .fla file, I create it by saying:

var unit00:Unit = new Unit(...);

So then it creates a gfx representation of the screen for me. I would like to have a method like this:


PHP Code:



public function remove ():Void {   unit_mc.removeMovieClip();   //deleting the gfx representation of the class in the .fla   delete instance of this;   //I want to delete the variable that references the instance of this class} 




So how do I get this to work? I know that delete this will not work when defined inside the class. How do I target the .fla's instance name when I don't know what it will be called?

Thanks for any assistance

Where To Place Onload() In Class
Hi I have created this class in a *.as file
this is the code that I have >>

Code:


class searchHandler {
// private instance variables
private var __searchQuery:String;
private var __searchQueryResult:String;

private var load_searchQuery:LoadVars;

// constructor statement
public function searchHandler( p_searchQuery:String ) {
this.__searchQuery = p_searchQuery;
load_searchQuery = new LoadVars();
load_searchQuery.searchText = this.__searchQuery;
load_searchQuery.sendAndLoad("http://mavrlz.mine.nu/ServerFiles/Rohit/Actual%20Project/searchResults.php", _root.load_searchQuery, "POST");

}
public function get searchQuery():String {
return this.__searchQuery;
}
public function set searchQuery(test:String):Void {
this.__searchQuery = test;
}

public function get searchQueryResult():String {
return this.__searchQueryResult;
}
public function set searchQueryResult(test:String):Void {
this.__searchQueryResult = test;
}
}



Code:

load_searchQuery.onLoad = function(success){
if (success)
this.searchQueryResult = load_searchQuery.response;
//this.searchQueryResult = "HELLO";
else
this.searchQueryResult = "Damnt IT ";
}


Everything works fine but where do I place the following function ? I tried placing it just after sendAndLoad(), no errrors flagged but it seems that onLoad() is't being called as the values aren't set

[CS2] Rotate In Place Using The Twen Class?
I'm trying to gt a circular symbol to rotate in place using the tween class. I gave the symbol an instance name of "carousel" and can get it to rotate 180 degrees, but it rotates around from the TOP of the circle, rather than the CENTER.


Code:
import mx.transitions.Tween;
import mx.transitions.easing.*;
var myTween:Tween = new Tween(carousel, "_rotation", Regular.easeOut, 0, 360, 2, true);
myTween.onMotionFinished = function() {
trace("myTween Finished")
};
Can anyone explain what I need to do to get the symbol to rotate from the center?

thanks!

Document Class - Putting Code In One Place Question
Hi there,

I'm trying to catch up with AS3. I just purchased "Learning ActionsScript 3.0" by O'Reilly. I read about using the document class, where they talk about removing your code from the timeline into .as class doc, which makes sense.

However, they don't seem to go much further into it other than a basic look.

If I have a fairly complex flash doc, does it make sense to put a majority of my code there still? To me it seems like it would be nice to be able to organize external .as files as a group instead of all in one document, but you can only load one document class .as that I can tell.

So if I have my document class like so:


Code:
package {
import flash.display.MovieClip;

public class Main extends MovieClip {

public function Main() {

trace('code here');

}

}
}
Would I need to put *all* my code for the whole fla in Main()? Or is there some other was to split it up into multiple .as documents? (Maybe importing other .as classes into Main?)

Instance Of Class Inside Of Different Class
I am trying to make an instance of a class inside of a different class. But I am getting an error:
**Error** C:Documents and SettingsOwnerDesktopSlideshowsFlashReminderE vent.as: Line 8: A class's instance variables may only be initialized to compile-time constant expressions.
var s1:Step = new Step();

**Error** C:Documents and SettingsOwnerDesktopSlideshowsFlashReminderE vent.as: Line 9: A class's instance variables may only be initialized to compile-time constant expressions.
var s2:Step = new Step();

**Error** C:Documents and SettingsOwnerDesktopSlideshowsFlashReminderE vent.as: Line 10: A class's instance variables may only be initialized to compile-time constant expressions.
var s3:Step = new Step();

**Error** C:Documents and SettingsOwnerDesktopSlideshowsFlashReminderE vent.as: Line 11: A class's instance variables may only be initialized to compile-time constant expressions.
var s4:Step = new Step();

**Error** C:Documents and SettingsOwnerDesktopSlideshowsFlashReminderE vent.as: Line 12: A class's instance variables may only be initialized to compile-time constant expressions.
var s5:Step = new Step();

**Error** C:Documents and SettingsOwnerDesktopSlideshowsFlashReminderE vent.as: Line 13: A class's instance variables may only be initialized to compile-time constant expressions.
var s6:Step = new Step();

The code for the first class is:
code:
class Event {
var type:String = new String();
var oName:String = new String();
var description:String = new String();
var steps:Number = new Number();
var dueDate:String = new String();
var percent:Number;
var s1:Step = new Step();
var s2:Step = new Step();
var s3:Step = new Step();
var s4:Step = new Step();
var s5:Step = new Step();
var s6:Step = new Step();
function createNewEvent(d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11) {
type = d1;
oName = d2;
description = d3;
steps = d4;
dueDate = d5;
percent = 0;
if (steps == 6) {
s1.createNewStep(d6);
s2.createNewStep(d7);
s3.createNewStep(d8);
s4.createNewStep(d9);
s5.createNewStep(d10);
s6.createNewStep(d11);
} else if (steps == 5) {
s1.createNewStep(d6);
s2.createNewStep(d7);
s3.createNewStep(d8);
s4.createNewStep(d9);
s5.createNewStep(d10);
} else if (steps == 4) {
s1.createNewStep(d6);
s2.createNewStep(d7);
s3.createNewStep(d8);
s4.createNewStep(d9);
} else if (steps == 3) {
s1.createNewStep(d6);
s2.createNewStep(d7);
} else if (steps == 2) {
s1.createNewStep(d6);
s2.createNewStep(d7);
} else if (steps == 1) {
s1.createNewStep(d6);
}
}
function showPercent() {
for (var p = 1; p<=steps; p++) {
percent += this["s"+p+""].percent;
}
percent /= steps;
return percent;
}
function done(stepN) {
this["s"+stepN+""].done();
}
function setStepPercent(stepN, p) {
this["s"+stepN+""].setPercent(p);
}
}

The class being loaded is:
code:
class Step{
var completed:Boolean = new Boolean();
var sName:String = new String();
var percent:Number = new Number();
function createNewStep(d1){
completed = false;
sName = d1;
percent = 0;
}
function setPercent(tbs){
percent = tbs;
}
function done(){
completed = true;
percent = 100;
}
}

Please help!!!

How Do I Refer To A Class Instance From Another Class?
Trying to get my head around scope here... I have the following in my root DocumentClass:

var horse1:Horse = new Horse();
var odds:OddsBox = new OddsBox();

From within the Horse class, how can I now refer back to the odds OddsBox instance?

My instinct is to type:
trace(_root.odds);
but that obviously doesnt work here.

Do I have to pass the odds var into the Horse class, in which case, would it have to be declared before the horse1 instance? If so, what if that is not possible - how do I refer to an outside class if it was declared after the calling class was declared?

Thanks lots

[AS2] Self Reference To A Class Instance Within A Class
Hello people!

The question says it, how can I self refer to an instance of a class within the class definition file?

Here is an example


PHP Code:



public function fireBullet(target:MovieClip) {
        Bullet_mc = target.attachMovie("Bullet", "Bullet1", 1);
        }
    } 




Now everytime I want to call the function I have to put this as my target, (fireBullet(this))I cannot just put it in the code as it gives me an error. Could someone please help.

[AS2] Self Reference To A Class Instance Within A Class
Hello people!

The question says it, how can I self refer to an instance of a class within the class definition file?

Here is an example


PHP Code:



public function fireBullet(target:MovieClip) {
        Bullet_mc = target.attachMovie("Bullet", "Bullet1", 1);
        }
    } 




Now everytime I want to call the function I have to put this as my target, (fireBullet(this))I cannot just put it in the code as it gives me an error. Could someone please help.

Any Way To For A Class Instance To Ask What Its Instance Name Is?
Hey. I have a class which needs to create a movie clip on the stage. Since each instance of the class will only ever have 1 movie clip on the stage at a time, it seems reasonable that I have the instance create a movie clip with its own name, prefixed with "mc_" or something of the sort.

Here's where I don't know quite what to do... How do I get at this information? For instance, when you a dealing with an XMLNode, you can simply use...

the_answer = xmlNodeInstance.nodeName;

...I know the analogy fails, but hopefully you know what I'm looking for.

Thanks!

Class And Instance
I have created about 10 movieclips (enemy1, enemy2....etc..) which all belong to a class called "C_enemy"

If I want to check if there is any hit on the enemies, I need to do this:

if (this.hitTest(this._parent.enemy1)) {
// do sth.
}
if (this.hitTest(this._parent.enemy2)) {
// do sth.
}
...
..
.

But it is too bulky, I don't want to do like this. I would like to know if I can write in one line like this:

if (this.hitTest(class of C_enemy?)) {
// do sth.
}

Get All Instance Of A Class
ok, I'm just wondering if there is a way to get references to ALL the instance for a defined class. Is there an array somewhere holding this? I try to find it but nah, no luck...

Any ideas guys?

A Class That Will Only Have One Instance Ever?
I have scripted an engine for a little game I'm making now. It has quite a bit of code of how to handle things, and some EventHandlers and stuff as well.
now, this engine wont always be used, like when the start-menu and other stuff are being shown.

so i get the feeling it should not always be around. what would be the best aproach for that?

should i make the whole engine into a class, and when it's needed i create an instance of that class?

I have sorta gotten the feeling before that classes are for things that there will be many instances of, but i could be wrong?

is there anything wrong with making a class that i know for sure there will never be more than one instance of? or is there a better aproach?

Thanks in advance =)

Get Class From Instance
How would I get a class from an instance? Basically im trying to compare two instances and see if they are of the same class. Thanks

[AS2 OOP] Best Way To Instance A Class?
Hello everyone. I love Kirupa!

I am wrapping my brain around OOP and I need some advice. I am making two posts on two different subjects.

My question here is: when should I link an AS2 class to a library symbol which I then instance, and when should I use “new” in code to create a new instance of a class? (Feel free to correct my terminology.)

Let’s say I have a menu for general system options. I want to define it in a class called MenuSystem. One of the methods I want to attach to it is “summon”, which makes the menu visible, plays a sound, and changes its contents based on context.

I make a symbol in the Library which lays out all the menu’s elements and give this symbol the linkage identifier “ID_menuSystem”.

It seems I have two ways I can create, initialize, and refer to this thing and darned if I know which is better practice.

***METHOD A:
Make the class MenuSystem extend MovieClip.

The class constructor does not do anything.

In the class, references to the menu clip’s methods are done thusly:
this._visible=true;

In the library, fill in the symbol’s AS 2.0 class as “MenuSystem”.

In my main code, in a startup initialization function, I create the menu on the stage with:
<MC to attach the menu to>.attachMovie(“ID_menuSystem”, “theMenuSystem”, depth)

And then call the method anytime by referring to the instance:
<path>.theMenuSystem.summon();

***METHOD B:
Don’t make the class MenuSystem extend MovieClip.

The class constructor takes an argument “attachTo” for the MC to which the constructed menu’s MC should be attached.

The class constructor has in it:
this.myMC = attachTo.attachMovie(“ID_menuSystem”, “theMenuSystem”, depth);

In the class, references to the clip’s methods are done thusly:
this.myMC._visible=true;

In my main code, in a startup initialization function, I create the menu with:
this.theMenuSystem = new MenuSystem(<MC to attach the menu to>);

And then call the method anytime by referring to the instance:
this.theMenuSystem.summon();

***QUESTION:
Which method should I use, A or B? My main priorities are, in order:
1) Make code that can scale up to be part of a rather complex application.
2) Make code which will be easily reusable in other projects.
3) Make code which is comprehensible to other (real) coders (me being a fake one).

???

Thanks very much for any advice you can give to someone who wants to do good OOP but is lacking much formal training.

Get Instance Name In A Class
Hello!
I have searched around a while, but couldn't find what i'm looking for.

I have created a class: Persons
when I make an instance of this class I want to get the name of this instance and save it as a static var (Array). I want to do this so that i later can call a static function to all instances.

Like this:
var noen: Persons=new Persons("John");
var neon: Persons=new Persons("Mike");
var neonnoe: Persons=new Persons("Karl");
Persons.jumpAll();

And then everybody jumps. (No mater what I called the instances.)

Does anybody know how to do this?
Thanks for your attention.

Mr Amod

Accosiating A Class To An MC Instance
hi, would love to know how you accosiate a Class instance with an MC instance in AS2.

this is not working:

Code:
myMCInstanceName = new myClass(arg0,arg1);

Accessing Var's Outside Of A Class Instance
Hi,

I've defined a variable in my main timeline, and I want it to be accessed from inside a function inside a class, but Flash keeps throwing errors at me, how do I do this?

boombanguk

AS2 Class Instance Delete
How do you delete an Object instance created from a Class?

Below is the class from TestDestroy.as


Code:
class TestDestroy extends Key
{
public var myListen:Object
public var aNumber:Number
public var aClip:MovieClip

function TestDestroy(clip:MovieClip)
{
this.aClip=clip
this.aNumber=10
this.myListen=new Object()

Key.addListener(this.myListen)

this.myListen.onKeyDown=this.killME
}

public function killME():Void
{
trace("kill")
delete this
}


}



Now in the flas movie i have


Code:
var destroyTest:TestDestroy=new TestDestroy(_root.Ball)

trace("destroyTest:"+destroyTest)


The trace returns undefined but i can access the Object properties etc.. hence the aNumber and aClip additions.

i cant delete the Object instance from inside the class or from the main timeline.

Obviously it cant find the object as it is undefined, but list the objects when published and its there!.

Very odd

I am transfering to AS2 from AS1 and may have missed something but it is quite confusing that and object instance can exist but cant be destroyed, but can be referenced!

Any pointers gratefuilly recieved

Cheers
JOn

How To Get Path Of Class Instance?
I'm creating a class which will call fscommand to request Javascript to send in some values. I want to pass the path to the class instance to fscommand so that in Javascript I use SetVariable to assign the instance values. But targetpath() doesn't work on classes or objects, only on movieclips. Is there a way that an instance of the class can determine its absolute path?

New Instance's Are Not Created From Class
Hello,
I have created a class called surverySlide in which I have linked to a bunch of slides. each slide registers how many questions it has to the class (itself). The problem is I need each movieclip to be its own instance of SurveySlide ( I have a surveyManager class built to deal with each. I am using attachmovie to show them in sequence on the stage (loading one after the other). I assumed by linking each movie clip to the class a new instance would be created each time but only one instance is created. I.e. the questions are put into an array that should be only for that instance but everytime a new instance is loaded it is added on to the array.

I don't know if I am explaining this clear enough so.....

in each instance of the class (which is a movie clip) I will register the question to that slide...

i.e.

slide instance 1

this.registerQuestion(1);
this.registerQuestion(2);

//if I output the array here I get 1,2

slide instance 2

this.registerQuestion(3);

//if I output the array here I get 1,2,3
//I want it to only output 3

Does anyone know off hand why this is happening?

Passing A Class Instead Of An Instance
Well,
in game.as

var slug = new bullet(alien,this.ship.x,this.ship.y);
this.addChild(slug);

in bullet.as
var alien:MovieClip;
public function bullet(hitTestObject:MovieClip,shipX:Num ber,shipY:Number){
alien = hitTestObject;
this.x = shipX;
this.y = shipY;
this.addEventListener(Event.ENTER_FRAME,
bulletMove);
this.addEventListener(Event.ENTER_FRAME,
bulletHit);
this.addEventListener(Event.ENTER_FRAME,
checkY);
}

public function bulletHit(event:Event){
if(this.hitTestObject(alien)){
alien.parent.removeChild(alien);
clearListeners();
}

}

So is there any way I can pass a reference of the alien class into the constructor of the bullet class, because I want all bullets to look for all aliens.

How Do I Get Ride Of This Instance Of My Class
In a class file I have code that instantiates another class:

var classHolder.TheClass = new TheClass();
addChild(classHolder);
classHolder.someFunction();

in the "TheClass" class I have the "someFunction" that does some stuff and then when it's finished it needs to get ride of itself...or rather the "classHolder" on the base class needs to be removed. This needs to happen from the "TheClass" class though. How do I do that?

Class Instance Problemo
here is the problem:
i have made an instance of a class on my maintimeline(frame one):

var x1:myClass=new myClass;

in the next step i have passed a movieclip to a public function in my class:

x1.effect(myMovieclip)

and the function effects myMovieclip , but when i make copies of myMovieclip only the last instance added to the maintimeline would be effected by the function. i want to use the same function for different displayobjects without having to make an instance for each of them:

var x2:myClass=new myClass;I
var x3:myClass=new myClass;I-----> don't want to use this
var x4:myClass=new myClass;I

Dynamic Class Instance
Code:
private var styleArray:Array = new Array;
private var styleVar:Boolean = false;
var newMyCellRenderer:Object;
private function setStyles():void {
for(var i:Number = 0; i<cArray.length; i++) {
newMyCellRenderer = new Object;
newMyCellRenderer = MyCellRenderer;
styleArray(newMyCellRenderer);
this.holderMC[cArray[i]].dropdown.setStyle("cellRenderer",styleArray[i]);
}
}

I'm trying to ultimately name a bunch of variables here to create new instances of the MyCellRenderer class. How can I do this?

Thanks.

Removing A Class Instance
I have a quiz that is coming up when a video hits certain cue points and only goes away and begins to play again when they answer the correct question. I am having a problem where I think the question class is still instantiated from the last question I answered because it goes away every time after the first question even if you answer wrong. Here is what I have tracing out for 3 questions (1 through 3):

Code:
//after I submit first:
submitting correct answer
close the quiz

//after I submit second:
submitting correct answer
close the quiz
submitting correct answer
close the quiz

//after I submit third:
submitting correct answer
close the quiz
submitting correct answer
close the quiz
you answered wrong
submitting wrong answer


So you can see when I submit its checking the current question plus all the previous ones. I need to know how to kill the previous one. Here is how I start each question:
code:
private function cuePointHandler(e:MetadataEvent):void
{
//trace(e.info.time);//time cuepoint was set
trace(e.info.name);//name of cuepoint
if(__answers[e.info.parameters.id] != "noquestion")
{
var q:VTODQuestion = new VTODQuestion(e.info.parameters.id,__answers,this);
}
else
{
trace("not a question..going to next cue");
}
}


I need to kill the q instance after Its done being answered. Anyone know how??

Remove Class Instance
Hi

I'm creating movieclips dynamically and assigning them classes


Code:
var subitem:MovieClip = this.createEmptyMovieClip("subitem"+step, this.getNextHighestDepth());

new subhoverlistener(subitem);
in the class :

Code:
public function subhoverlistener(clip:MovieClip) {
this.clip = clip;
Mouse.addListener(this);
}
the problem is that after I remove all these clips


Code:
for (var i:Number = 0; i<step; i++) {
this["subitem"+i].removeMovieClip();
}
the class instances seem to remain because after I create new set of movieclips without
new subhoverlistener(subitem);
they still act like this class is assigned...
How can I remove the class reference?

Class Instance Suicide
Can I destroy a class instance from within itself.

I've tried using delete(this) but it returns false.

Do I need to delete the variable assigned to it when it was created?

Thanks

Passing A Class Instance To A MC
Hi guys, ehm... I know I'm quite late but...

I'm going to rewrite a 10.000 lines app wrote in as1, in as2. And soon, I've just found out that's still impossible to "connect" MCs to classes... I'll be more clear; writing:


Code:
_level0.attachMovie("libName","pippo",10, new myClass(initVal,[otherStuff]));
I can't call myClass methods in the MC. MC inherited ONLY myClass properties, not methods.

please tell me I'm stupid, tell me I miss something!...

ciao

Passing A Class Instead Of An Instance
Well,
in game.as


ActionScript Code:
var slug = new bullet(alien,this.ship.x,this.ship.y);
this.addChild(slug);

in bullet.as

ActionScript Code:
var alien:MovieClip;
public function bullet(hitTestObject:MovieClip,shipX:Num ber,shipY:Number){
alien = hitTestObject;
this.x = shipX;
this.y = shipY;
this.addEventListener(Event.ENTER_FRAME,
bulletMove);
this.addEventListener(Event.ENTER_FRAME,
bulletHit);
this.addEventListener(Event.ENTER_FRAME,
checkY);
}

public function bulletHit(event:Event){
if(this.hitTestObject(alien)){
alien.parent.removeChild(alien);
clearListeners();
}

}

So is there any way I can pass a reference of the alien class into the constructor of the bullet class, because I want all bullets to look for all aliens.

Dynamic Class Instance?
Hello,

I wanna know if I can create class instance from string, something like this.

ok:String = "className";

new ok();
or
new "className"();

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

Instance Name In MovieClip Class
How can I acess a instance name from a class of a movieclip?

How Do I Reference An Instance From A Different Class?
the 1stclass creates an instance we will call X.

the 2ndclass references X just fine through MovieClip(parent)X.whatever

that same 2ndclass also references an instance called Y from a 3rdclass.

-here is the trouble-
in the 3rdclass (that Y comes from) i need it to also reference the same instance X that was created back in the 1stclass.

what do i use to direct the class to the instance i want it to reference???

ive tried MovieClip(parent)
ive tried MovieClip(parent).1stclass
and every combination of .somethingelse

if anyone can enlighten me on this i will be even more grateful than what i already am because you even read this.

thanks,
zach

How To Determine If Something Is Instance Of A Class
hello;

I am working with papervision3d;

I have collada_model.material and I want to know if it is an instance of the MaterialObject3D class;


any thoughts?


thanks
Shannon

How To Access MC By Instance Name From Within A Class?
I have an app that has some display objects already on the stage in the .fla. Let's say I have a text field with the instance name myTitle on the stage. If I want to access that text field (or any other named instance on the stage) from within a class that I'm writing, how do I do so? I would normally just use:

myTitle.text = "new text";

but I don't seem to be able to access instance names this way. I've tried making the class a display object and adding it to the stage/display list to see if that would help, but I have the same problem. How do I go about doing this?

Thanks in advance...

How Can I Target An Instance From Within A Class?
Hi Guys,

I added (addChild) a movieclip on the stage.
Now I have a class and I want to target the dynamically
added movieclip's size. How can I do that?

Thanks a lot

How Do I: Access Instance From Class.
how do i access a movieclip instance in the main FLA file from a class file imported by the main FLA file?

i'd like to addChild() to a movieclip instantiated in the FLA from a class file.

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