Vlad the Impala
Vlad the Impala

Reputation: 15872

Choosing a Class Dynamically in Actionscript 3

I have a line of code like this:

var myObj:[SomeClass] = new [SomeClass]();

I want to choose which class this object will belong to randomly at runtime. Is there a way to do this in Actionscript 3?

Upvotes: 0

Views: 210

Answers (6)

bhups
bhups

Reputation: 14875

I don't think there is any direct way to do this. But you can try this thing.

var funcArray:Array = new Array();

public function getObjClass1():Class1 {
  return new Class1();
}
...
...
public function getObjClassN():ClassN {
  return new ClassN();
}
//add all functions to funcArray array
public function addFunctions():void {
  funcArray.push(getObjClass1);
  ...
  funcArray.push(getObjClassN);
}

public function getRandomObject():* {
  return funcArray\[Math.floor(Math.Random() * funcArray.length)\]();
}

Upvotes: 0

grapefrukt
grapefrukt

Reputation: 27045

This is what just somebody's answer would look like in proper AS3 syntax.

var classes:Array = [Foo, Bar, Baz];
var myObj:YourSuperclass = new classes[int(Math.random() * classes.length)];

If the classes do not have a common superclass you can keep myObj untyped.

Upvotes: 0

Vic
Vic

Reputation:

I suggest the following if you have several classes: Class1, Class2, Class3 who all extend AbstractItem

var itemClass:Class = getDefinitionByName("com.packagename.Class" + Math.floor(Math.random()*3 +1)) as Class;
var item:AbstractItem = new itemClass();

Upvotes: 0

ablerman
ablerman

Reputation: 1543

I think you should be able to do something like:

var classes:Array = [Class1, Class2, Class3];
var obj:Obj = new classes[0];

Each class will probably have to implement a shared interface to make it useful. So it would look something like:

var classes:Array = [Class1, Class2, Class3];
var obj:IInterface = (new classes[0]) as IInterface;

Upvotes: 0

Amarghosh
Amarghosh

Reputation: 59451

Here comes Object Oriented Programming:

Declare your variable's type as a common super class's type (or an interface) and extend (or implement) all the possible classes from that super class (or interface).

public class MyType
{
}
public class Type1 extends MyType
{
}
public class Type2 extends MyType
{
}
public class Type3 extends MyType
{
}

var something:MyType;
//Now you can do
something = new Type1();
something = new Type2();
something = new Type3();

Here is a sample using interfaces:

public interface MyType
{
}
public class Type1 implements MyType
{
}
public class Type2 implements MyType
{
}
public class Type3 implements MyType
{
}

Upvotes: 0

just somebody
just somebody

Reputation: 19247

I don't know how well this would fly in AS3, but in JS, I'd use

var classes = [foo, bar, baz];
var myObj = new_(classes[random() % 3])();

maybe it'd work in AS3 too?

new_ is part of Zeta (http://codex.sigpipe.cz/zeta/docs/reference.rest#new-cls), random() is pulled from thin air.

Upvotes: 1

Related Questions