How to (Or can I) edit variables from inherited class

I have a class Character that has the variables

int health;
float movementSpeed;
float attackSpeed;
//etc...

And I want to create another class (say Brian) who inherits from the class Character and thus already has those variables assigned to him:

public class Character_Brian : Character
{
    health = 100;
    movementSpeed = 1.3f;
    attackSpeed = 1.2f;
    //etc
}

(Of course this doesn’t actually work, but it hopefully paints the picture of what I want to do)

This is so that I can do something like displaying values that can vary on places such as healthbars, like

public class HealthBar : MonoBehaviour
{
    health = Character.health
}

so that I don’t have to write an if else tower for each character available

Is this possible to do? And if not, what would be the best way of doing it?
Thanks in advance :)

Really smells like you want some of these babies: fresh piping hot ScriptableObjects!

1 Like

You need to make those variables non-private first.
You can add the public modifier to them, which allows them to be accessed by any other object, or you can add the protected modifier to them, which allows only child objects to access them.

If you want to initialize those variables from the child class, there’s a couple ways to go about it.

If the parent class is a MonoBehaviour
You can set the initial values from the Awake or Start method:

public class Character_Brian : Character
{
  void Awake()
  {
    health = 100;
    movementSpeed = 1.3f;
    attackSpeed = 1.2f;
  }
}

If the parent class is a plain C# object
You can set the initial values from a constructor:

public class Character_Brian : Character
{
  public Character_Brian()
  {
    health = 100;
    movementSpeed = 1.3f;
    attackSpeed = 1.2f;
  }
}

You could even define a constructor that takes in these values as parameters in the parent class to initialize them there, if that’s what you prefer:

public class Character
{
  protected int health;
  protected float movementSpeed;
  protected float attackSpeed;

  public Character(int health, float movementSpeed, float attackSpeed)
  {
    this.health = health;
    this.movementSpeed = movementSpeed;
    this.attackSpeed = attackSpeed;
  }
}

public class Character_Brian : Character
{
  public Character_Brian() : base(100, 1.3f, 1.2f) {}
}

But I’d say the ScriptableObject approach mentioned above may be better for this in general.