- Home /
Upgrading a Custom Class into an Inheriting Class
Let's say my game has a party system, and perhaps a storage for characters which are not in the player's party (such as a town). When a character is in storage, there are only a few properties it needs, perhaps "Name," "Strength," and a list of abilities would do.
public class Character
{
public string Name;
public int Strength;
public Ability[] Abilities;
}
This is fine and all, and won't take up too much space when saving the game. But now our poor, poor character joins our party and needs new properties. I've created a larger class which inherits the Character class and adds some neat stuff to work with.
public class PartyCharacter : Character
{
public int CurHealth;
public Enemy Target;
}
Here's where my problem rises; true to the title, I'm uncertain how to transform a Character class into a PartyCharacter class. This is what I'd like to do:
Character JohnDoe = new Character();
PartyCharacter Leader = (PartyCharacter)JohnDoe;
Needless to say that doesn't work. Possibly noteworthy: I'd like to create a constructor for both classes, both of which would calculate/randomize the character's stats. Also, how would transforming a PartyCharacter to a Character work?
Answer by Horschty · Jun 04, 2018 at 07:55 PM
How about this:
public class Character {
public string Name;
// Copy constructor which allows you to make a copy of itself
public Character(Character other) {
Name = other.Name;
}
}
public class PartyCharacter : Character
{
public int CurHealth;
public Enemy Target;
// Here you call the base copy constructor,
// which then copies the passed in characters fields into THIS instance
public PartyCharacter(Character character) : base(character) {
}
}
...
Character character = new Character();
character.Name = "Peter";
PartyCharacter partyCharacter = new PartyCharacter(character);
// partyCharacter.Name should now also be Peter
Answer by ShadyProductions · Jun 04, 2018 at 08:32 PM
Horschty's answer is the most accurate to get what you want to achieve.
It's impossible to cast Character to it's derived class.
For example, I can't cast a car into a ferrari, it might be a honda.
But you can however cast from your derived class to your base class.
For example, I can cast this honda into a car, because it's a car.
Your answer
![](https://koobas.hobune.stream/wayback/20220612164011im_/https://answers.unity.com/themes/thub/images/avi.jpg)