I'm building a mod for Terraria that will add classes and their corresponding abilities to the game. You're a warrior? Push your ability key and you'll use your berserk ability.
I'm trying to make my player code as simple as possible. I'd like to set the player's in-game "class" by doing something like this at the top of the player class so the rest of the methods in it can access it later:
//Set class WarriorClass playerClass == new WarriorClass(playerReference, level) Herein lies the first issue. I get an error at playerReference that says:
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'ModPlayer.playerReference' MyMod Ok, so I looked that up and set the initialization in the WarriorClass instead:
public Player playerReference = new Player(); And I have this now in my player code:
//Set class WarriorClass playerClass = new WarriorClass(level); Here's the beauty of it. In the gamepad input method within my player code all I ever have to do is:
//On key presses public override void ProcessTriggers(TriggersSet triggersSet) { if (MyMod.ability1Key.JustPressed) { playerClass.UseAbility(MyMod.ability1Key); } Now that the ability1 key was pressed, let the WarriorClass handle what to do:
public void UseAbility(ModHotKey key) { //Ability 1 if (key.JustPressed == MyMod.ability1Key) { //Start berserking if (player.HasBuff(ModContent.BuffType<BerserkBuff>()) == false ) { //Lose 10% of your life lifeLost = player.statLifeMax2 / 10; player.statLife = player.statLife - (int)lifeLost; //Berserk and add damage over in the Buff code player.AddBuff(ModContent.BuffType<BerserkBuff>(), 600, false); } This is all great!!! I can add any amount of classes I want and this player code never changes. Except If I want to add if/then logic to select a class in say, Update() then it breaks the following reference in my gamepad input code:
playerClass.UseAbility(MyMod.ability1Key); Of course it won't have a reference unless I hard code it at the top of the player file, but I don't know what class a player will be until they pick one.
Am I doing this fundamentally in a bad way or am I missing something else in terms of OO programming? I don't want to have to initialize every class for the character at the top of the file like this:
WarriorClass warriorClass = new WarriorClass(level); ArcherClass archerClass = new ArcherClass(level); ... ... just to do this in the gamepad input method:
if (classChoice == "Warrior") { warriorClass.UseAbility(MyMod.ability1Key); } else if (classChoice == "Archer") { archerClass.UseAbility(MyMod.ability1Key); }