- Home /
How to inherit from two classes?
I've already look around for an answer to this, and most answers involve partially cheating monodevelop to inherit two classes and usually causes errors. I'm stuck wondering is there a way to just literally inherit two classes?
I've got an Inventory class which contains functions such as AddItem() and RemoveItem(), and then I have the tile functions class (It's a tile based game), which involves functions like PlantCharge(), UnscrewVent(), TakeHostage() (It's a heist game).
I'm going to need to be able to use a script to say that if I click on a wall while a breaching charge is selected, call functions PlantCharge() to plant the charge, and RemoveItem() to take the charge from the players inventory once he places it. I've inherited from Tile functions, but I can't get the equippedItem variable that I'm using to detect which item the player is holding.
So there, I'm stumped. I'd have expected that Unity would have a method of inheriting from two classes, or, at least I don't know if it has.
What would this class be that would inherit from both an inventory and a tile? I think your design is a bit flawed. I would think that the player class would have an instance of an inventory and a reference to the current tile the player was standing on. That way, when handling the input for the player, you would remove from the players inventory and place an object on the current tile the player is on. No object should contain both the functionality of a tile and an inventory at the same time (well, at least not in your case).
Answer by Kiwasi · Sep 23, 2014 at 02:10 AM
There is no way to inherit from more then one class.
What you can do is implement an interface, which is pretty close.
Another option is to use reflection to figure out what methods are available. I would advise against this unless you have no other option. In many cases reflection can be avoided by using the right structure.
Alright. I'm gonna try to implement one of these "Interfaces".
Answer by Habitablaba · Sep 23, 2014 at 09:37 PM
The inability to inherit from two classes at once is not actually related to Unity at all, but a 'limitation' of the programming language.
There are actually quite a few ways to accomplish what you are asking for, but I think you may not be trying to solve this problem in the 'best' way possible. You are coming at this from an Object Oriented standpoint, which often times will find you in uncomfortable places with Unity.
Instead of thinking in strictly IS-A and HAS-A relationships, like you might in an OOP environment, think more in terms of how each object is meant to behave. Remember that each GameObject can have more than one script attached to it, so you you could have a script simply to manage the player's movement as well as a script to handle the placement of explosives or unscrewing of a vent.