PDA

View Full Version : How do you dynamically call a class (using vars) in AS3


Marsoups
06-05-2008, 09:42 AM
Hi all,

Let's say I have two classes :

package {
public class B1 {
function B1() {
trace("CLASS B1 INSTANTIATED");
}
}
}



package {
public class B2 {
function B2() {
trace("CLASS B2 INSTANTIATED");
}
}
}


Now in my main movie, I want to create an instance of one of these classes, but I wish to do so dynamically, by referring to the name of the class in a variable, if you catch my drift. So let's say I have an array with the names of the classes :

var number = 1;
var classname = "B"+number;
var newinstance = new classname;


How can this be achieved ? I get this error if I define classname as a class:


TypeError: Error #1034: Type Coercion failed: cannot convert "B1" to Class.
at classtest_fla::MainTimeline/classtest_fla::frame1()

lordofduct
06-05-2008, 09:47 AM
flash.utils.getDefinitionByName

over at livedocs, links in my siggy

Marsoups
06-05-2008, 09:56 AM
cheers lord, you're a champ !!!:cool:

Marsoups
06-05-2008, 10:34 AM
Getting a strange error though...

Here's my code..


var newstring:String = "B"+2;
var classname:Class = getDefinitionByName(newstring) as Class;
var th:Object = new classname();

Results in this error :

ReferenceError: Error #1065: Variable B2 is not defined.
at global/flash.utils::getDefinitionByName()
at classtest_fla::MainTimeline/classtest_fla::frame1()

Marsoups
06-05-2008, 10:47 AM
ok i tried this...


var ClassReference = new (getDefinitionByName(newstring));

Marsoups
06-05-2008, 12:14 PM
still not working, if i have not made an instance of the class... i need to be able to tell what classes are accessible somehow i guess..

Marsoups
06-05-2008, 12:27 PM
so any ideas ??

to put it in short, how can you create an instance of a class that you have loaded into the library using applicationdomain (however not createed an instance of yet), when you want to dynamically make an instance of a class according to a string formula eg. "B"+2

Marsoups
06-05-2008, 12:55 PM
Simplest idea i could come up with to solve this, if anybody in the future needs to know...

you have to create a reference to it somehow in the source.

easiest way to do it is to make an array.

var classarr = [B1,B2,A]; // references to the classes here.. (no instances tho)

Then do a check for the class and it'll pick it up..

lordofduct
06-05-2008, 04:20 PM
I've used this method before, and it worked for me. Here's two ways I just tested it and it worked find (this was with a library item I created linkage of with the name "Test").


var classRef:Class = getDefinitionByName("Test") as Class;
var sym:DisplayObject = new classRef();
addChild(sym);

worked


var sym:DisplayObject = new (getDefinitionByName("Test"))();
addChild(sym);