- Home /
Constructors for Only-Realtime-Created Monobehaviours
What are the risks of using constructors for MonoBehaviours that will NOT be serialized/deserialized, as they are created and destroyed in run-time.
I know i can use awake, but for some reason I don't want to, please provide answers about the question itself, not suggestions for alternative approaches.
Thanks.
Answer by whydoidoit · Mar 04, 2014 at 10:01 AM
I can't think of any risks under those circumstances. But given you are going to have to create a parameterless constructor (because you can't construct any MonoBehaviour directly, only through AddComponent) it won't be very different from Awake.
sure it's not different, but i'm using inheritance, if the base class had a constructor, it's guaranteed that it's gonna get called, but if it had protected virtual Awake(), it might be overriden without calling base.Awake(), or calling base.Awake() later, that's why i prefer having a constructor, i don't want to give the derived class control over when and if the initialization method is called.
Agreed, those are the only circumstances I can see it being useful under.
BTW - the way Unity works Awake never needs to be virtual because it's reflection method calls top down. As long as the base classes have protected, internal or public Awake functions you can call them. I ended up doing it this way, but the limitations are as you say.
you mean that if i had non-virtual private awake in the base and the derived classes, both are gonna get called, and the base first? If so, it's new to me, and then I'm gonna go with "Awake" solution
Sadly not - I mean simply you can avoid all of the
protected virtual void Awake() {
}
and
protected override void Awake() {
}
in favour of
protected void Awake() {
base.Awake();
}
Technically makes the class smaller and reduces typing, but doesn't help with the enforced downwards calls.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
constructing buildings rts style. 1 Answer
Displaying buildable area as an overlay on terrain 0 Answers
Flip over an object (smooth transition) 3 Answers