Skip to main content
Inspiring
January 31, 2015
Answered

How to assign new object to class?

  • January 31, 2015
  • 2 replies
  • 391 views

So I know how to do this:

var classexample:objectexample = new objectexample();

But I'm attempting to make a game where you can select a character and that selected character's object assigns to the class, but I don't know how to get it to change. As far as I know I can only assign it once and then that's it, I dunno how to change it. Is there a way how?

Example, I know this doesn't work, but I'd like to do something like this:

if(character=="example1"){

var classexample:objectexample1 = new objectexample1();

}

if(character=="example2"){

var classexample:objectexample2 = new objectexample2();

}

Any ideas?

This topic has been closed for replies.
Correct answer Twisted4000

I got it to work!

All I had to do was set up the initial var for the object, so:

var p1;

Then, if the variable changed in the character selection, all I had to do was:

if(p1_character=="character1"){

p1 = new character1();

}

Bam!

2 replies

Twisted4000AuthorCorrect answer
Inspiring
January 31, 2015

I got it to work!

All I had to do was set up the initial var for the object, so:

var p1;

Then, if the variable changed in the character selection, all I had to do was:

if(p1_character=="character1"){

p1 = new character1();

}

Bam!

kglad
Community Expert
Community Expert
January 31, 2015

for different objects (eg, characters) that will share common characteristics/code (eg, a player class) you would assign each a different (eg, character1, character2 etc) class but have each extend the same super (eg, player) class.

Inspiring
January 31, 2015

Alright, makes sense. However, is there a way I can change the instance names of these classes for AS3 to access them? Because in each character's function script, they use the same identifier name (like even though the characters are different, all the characters for player 1 will still use "p1" and for player 2 "p2"), it makes it easier for them to interact with each other.

This is what I use to set up the characters manually:

var p1:character1 = new character1();

"character1" being the class of the MC. I want to make a script that, when a different character is selected, I can change the class to character2, character3 etc, how would I be able to change that class for "p1"? (Sorry if I'm getting classes and objects confused, I think I am)

kglad
Community Expert
Community Expert
January 31, 2015

p1 can be assigned to any character (or anything else) class.  you can also coerce strings into classes using getDefinitionByName() function.

eg, if you have something like a combobox where users select a character, you can use a string for the class name and assign something like:

var charClass:String = combobox.selectedItem.label;

var p1:*=Class(getDefinitionByName(charClass));