Legacyblade
Legacyblade

Reputation: 335

ActionScript3: Inheriting constructor arguments from parents

I'm making a game in action script 3. In it, I have an actor class from which player and enemy classes will be derived. I'm doing this so that unless I need to provide specific AI or fancy behavior (such as for bosses), I can just make a new clip in the library for each enemy without making an actionscript file.

However, I've run into a problem.

Whenever I try to pass arguments to the construction of an enemy (make it spawn with more health), I get error 1136 (Incorrect number of arguments.)

This is because the constructor created automatically at runtime doesn't have the same arguments as it's parent class. Is there any way to get around this without making a class file where I copy and paste the parent constructor function for each of my hundreds of enemies?

Upvotes: 0

Views: 496

Answers (2)

francis
francis

Reputation: 6349

Edit actually rereading your question I think you may be looking for super();

Example

public class Actor{
 private var myHelth:uint;
     public function Actor(helth:uint = 100){
         myHelth = helth; //this will be set to 100 if nothing it passed in or the value passed
    }
}

Class that extends Actor:

public class Boss extends Actor{
     public function Boss(){
          super(200); //passes 200 to Actor;
     }
}

If you're trying to pass data into a classes constructor you need to make sure it's accepting arguments.

public class Actor{
     private var myHelth:uint;
     public function Actor(helth:uint = 100){
         myHelth = helth; //this will be set to 100 if nothing it passed in or the value passed
     }
}

Then to use

 var a:Actor = new Actor(200); //setting health to 200

 var b:Actor = new Actor(); //using the default of 100

Upvotes: 1

Jason Sturges
Jason Sturges

Reputation: 15955

Make sure your symbols in Flash Pro have appropriate AS linkage, then use pass constructor arguments in super statements:

Actor - base class

package
{

    public class Actor
    {
        public function Actor(name:String, role:String)
        {
        }
    }
}

Player - inherits from Actor defining its own constructor parameters:

package
{

    public final class Player extends Actor
    {
        public function Player(... params:Array)
        {
            // pass desired inherited constructor parameters
            super("name", "role");
        }
    }
}

Enemy - inherits from Actor defining its own constructor parameters:

package
{

    public final class Enemy extends Actor
    {
        public function Enemy(... params:Array)
        {
            // pass desired inherited constructor parameters
            super("name", "role");
        }
    }
}

Upvotes: 0

Related Questions