- Home /
How do I set default values for inherited variables such that they keep their values when added by script?
Very basic example:
public class A : MonoBehaviour
{
public int a = 1;
}
public class B : A
{
void Reset()
{
a = 5;
}
}
public class C : MonoBehaviour
{
void Start()
{
B b = AddComponent<B>();
}
}
If B is added to an object in the editor, 'a' does get set to 5. However, if C is put on an object, that object gets a B with 'a' == 1. I think this is the kind of thing that would usually go in a constructor, but MonoBehaviours are not supposed to use constructors. I could make an extra function to set the values that is called in both Start and Reset, but then changes made in the editor would be ignored. The only solution I can think of is to make B.Reset public, and add:
public class D : MonoBehaviour
{
void Start()
{
AddComponent<B>().Reset();
Destroy(this);
}
}
and then add a D whenever I actually want a B. Is there some other, simpler way to do this?
Actually constructors on $$anonymous$$onoBehaviours is just fine, as long as you don't attempt to Destroy anything, or add another $$anonymous$$onoBehaviour in the constructor. For custom classes and primitive data, a Constructor will have zero issues from a $$anonymous$$onoBehaviour.
Your answer
![](https://koobas.hobune.stream/wayback/20220612121909im_/https://answers.unity.com/themes/thub/images/avi.jpg)