- Home /
Set value of a variable of a parent class - c#
I have a base abstract class Hero with a protected int health in it. I have a second class Mage which inherits Hero. I want to set a health value for the mage. health = 5; -> not working, it says its a field but is used as a type What do i do? How do i set values for all the types of heroes?
What you said you're doing is O$$anonymous$$. A protected field is visible for derived classes, and assignment works like always, so you're probably doing something more, share the exact code you're using and the exact error message.
@DiegoSLTS public abstract class Hero : $$anonymous$$onoBehaviour { protected int health; }
public class $$anonymous$$age: Hero { health = 10; }
Thats what im doing. :( Help!
What you said you're doing is O$$anonymous$$. A protected field is visible for derived classes, and assignment works like always, so you're probably doing something more, share the exact code you're using and the exact error message.
Answer by thousandcranes · Aug 29, 2016 at 04:54 AM
holy smokes! you should set value in the constructors! like this: Child class:
public Mage () { health = 10; }
Answer by DiegoSLTS · Aug 28, 2016 at 06:26 PM
You can't override the health value like that. You have to set a different value inside some function, like Awake for example:
public abstract class Hero : MonoBehaviour {
protected int health;
}
public class Mage: Hero {
void Awake() {
health = 10;
}
}
public class Archer: Hero {
void Awake() {
health = 15;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612091701im_/https://answers.unity.com/themes/thub/images/avi.jpg)