What's the best way to initialize object derived from monobehavior?

Viewed 167

We can't use constructor in class derived from Monobehavior, so we define "Initialze" method to simulate constructor, defination like this:

public class Animal : Monobehavior
{
    public void Initialize(string animalName)
    {
        // initialze animal
    }
}

Then, there is is dog class, which has different initialize parameter list:

public class Dog : Animal 
{
    // Cannot override because different parameter list
    public void Initialize(string animalName, Bone favoriteBone)
    {
        base.Initialize(animalName);
        // initialze dog
    }
}

Then, we create animal object like this:

var animalInstance = Instantiate(animalPrefab);
animalInstance.Initialize("animal name");

And we create dog object like this:

var dogInstance = Instantiate(dogPrefab);
dogInstance.Initialize("dog name", new Bone());

There is the problem, we can still call the "dogInstance.Initialize("dog name")" without Bone parameter, unlike C# constructor, if someday I'm drunk and write down the stupid code (or someone else come to write it), it's a big trouble.

So, is there a best way to initialize object derived from monobehavior?

1 Answers

You can branch out the instantiation of basic animals. You can make the Animal class to be an abstract base class (with its Initialize(string) being protected).

From Animal you can derive SimpleAnimal that will be used instead when you want to instantiate some basic animal. Then you will have Animal to derive from and SimpleAnimal to instantiate.

E.g. like

public abstract class Animal : MonoBehaviour
{
    public string Name { get; private set; }

    protected void Initialize(string animalName)
    {
        Name = animalName;
    }
}

public class Dog : Animal
{
    public void Initialize(string animalName, Bone favoriteBone)
    {
        base.Initialize(animalName);

        // initialze dog
    }
}

public class SimpleAnimal : Animal
{
    public new void Initialize(string animalName)
    {
        base.Initialize(animalName);
    }
}
Related