- Home /
C# Multiple constructors
Hey guys. I haven't exactly hit a problem with this, but I figured I'd learn about it before trying to go any further with it. I've got an "Enemy" class, currently, and want to have a way to create a new enemy with either a full list of variables, or just with an enemy id. I currently have this,
public class Enemy
{
public mUnit pMob;
public Enemy(int id)
{
this.pMob.enemyId = id;
}
public Enemy(int id, int hp, int spd, Equipment equipped, pStat stat, mDOMAIN dom, mCLASS c, mSEX g)
{
this.pMob.enemyId = id;
this.pMob.health = hp;
this.pMob.speed = spd;
this.pMob.items = equipped;
this.pMob.stats = stat;
this.pMob.domain = dom;
this.pMob.eClass = c;
this.pMob.gender = g;
}
}
Is this the proper way to create multiple class instantiation options, or should I be doing something else?
Answer by XD716 · May 27, 2014 at 04:32 PM
Give default values to your class variables, making them optional parameters.
public Enemy(int id, int hp = 0, int spd = 0...) {
}
Answer by Owen-Reynolds · May 27, 2014 at 06:56 PM
Another common method is to route them all through an init()
function. That allows you to make constructors taking any sorts of inputs. Ex:
// if it turns out you sometimes spawn enemies only varying on class&sex:
public Enemy(mClass c, mSex s) { init(100,0,0,0, c, s); }
// ...and often want to copy an old enemy, but with a different weapon:
public Enemy(Enemy e2, Equipment newGun) { init(e2.hp, ... , newGun, e2.class ... ); }
// copy of your 2nd "long" constructor
// all contructors call this to do the real work:
void init(int id, int hp ...... ) { ... }
But not really Unity tricks. This is all just general programming. C# forums are full of this stuff.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Handling multiple tags 1 Answer
Code design issue 3 Answers