Say I have these five classes:
Can I combine these classes by multiple Inheritance to a class "Boys" that inherits from "Males" and "Children" at the same time? In both UnityScript and C#? If so, how?
And if so, how can I make sure that I won't inherit from "Children" and "GrownUps" at the same time? (Would it give me an error or would one be overridden the other? If so, which one?)
Thanks & Greetz, Ky.
I think most modern languages - including C# and UnityScript - have abandoned the concept of multiple inheritance. The reason is that it creates more problems than it solves, and in the end, it doesn't really give you much benefit. Usually, you can use interfaces (at least in C#) if you need different "types" of classes to provide the same methods.
To be honest, usually the need for multiple inheritance comes from design flaws - as your example illustrates: Instead of having this complex inheritance hierarchy with Females, Males, Children and GrownUps, your People class would be fully sufficient. Instead of using the Start method to somewhat statically assign the attributes the People class defines, you'd either assign those variables from script, or in the editor.
In the context of Unity, you could use one other concept I know is used to live peacefully without multiple inheritance: composite aggregation, i.e. creating composite objects that consist of multiple smaller objects. That's exactly what GameObjects are in Unity: A composite object that consists of one or many components.
So, you'd have your People class which defines the attributes people have (gender, age, name etc.), and a few MonoBehaviours which model the behaviors that females, males, children and grownups usually share (the methods / functions you have defined above). That way, you'll always attach "People" to your GameObject (and probably, you'd call it "Person" instead of people, as instances of that class are not "people" but just one single person).
Then, depending on what kind of person it is, you could add "MalePerson" or "FemalePerson", and "Adult" or "Child", which implement the methods you have defined above. You could even do some extra checks from "Person" that prevent that one game object is both male and female or both adult and child (if that makes sense in your game).
That way, I'd say you can do pretty much exactly what you want to do without having to use multiple inheritance - instead you use elegant, modern, object oriented software design ;-)
answered Dec 23 '09 at 06:45 PM
You can do what you're describing, but note that the Unity invoked functions, such as Start and Update, do not behave like normal functions. Unity will always and only call those functions in the most derived class.
If you attached the derived script to a GameObject, the Start function will never be called. It must be in Derived for it to work, and no, making it virtual does not help the situation.
answered Dec 23 '09 at 04:34 PM