I want to be able to call a particular method automatically upon construction of a derived object, however I can’t think how to do it. The following code illustrates. Another answer recommended OnLoad, but I am doing this for Unity on Mac and OnLoad doesn’t appear to be supported by my platform. Any suggestions?
public class Parent {
public Parent ()
{
// A. Stuff to do before child constructor code runs
DoThisAutomaticallyAfterConstruction();
}
public void DoThisAutomaticallyAfterConstruction()
{
// C. In this example, this will run after A, before B. I want it to run ABC
}
}
public class Child : Parent {
public Child () : base()
{
// B. Stuff to do here after parent constructor code runs
}
}
Unfortunately there’s no built-in way to do what you want (it’s a fairly-often-requested feature).
One workaround is to implement a factory pattern, where you don’t create objects by calling the constructor directly, but instead implement a static method to create them for you. For example:
then add:
and instead of doing
you can do