- Home /
Inheritance structure
Hello all,
I have some difficulties managing inheritance in C#. I'm writing a game in which the player builds all sorts of machinery; this can be anything, from relatively simple objects (such as simple containers/boxes) all the way to something more elaborate; let's use a coal extractor as an example. I want to inherit certain behaviours from my simple objects in the more complex objects. To give a concrete example:
The coal extractor needs two basic behaviours:
The behaviour of a container (to store the extracted coal, and also so that the player can interact with it in the same way as it does with a box and move the coal from the extractor's internal storage into the inventory)
The behaviour of an electrically powered device (to be able to interact with the electric network, to know whether there is sufficient power in the electric grid etc.)
I hae two classes, Container and ElectricSink, which would do just the job, but C# won't let me inherit from two classes. Moreover, I not only need the behaviour (implementation of methods) from the those two classes; I need my Extractor to actually pass is-a type tests. This is because when the player interacts with an object, the type of interaction gets chosen by a piece of code that has different behaviours based on type. So, when I want to take the coal out of the extractor, I need it to go through a is-a Container test.
This can't be achieved with the interface trick, where you store instances of objects that implement different interfaces, because the underlaying class holding those objects still cannot itself pass the type testing.
Any ideas as to how I can solve this issue? Thanks!,
Answer by Hellium · Sep 15, 2020 at 07:21 AM
Unity encourages you to adopt the Composition over inheritance principle and this is clearly the solution to your problem. Keep the two classes but don't try to make one inherit the other.
Keep your container class, attach it to your object and make your CharcoalExtractor class not inherit from Container but just use it. Same for your electrical powered class.
EXAMPLE:
[RequireComponent(typeof(Container))]
[RequireComponent(typeof(ElectricMachine))]
public class CoalExtractor : MonoBehaviour
{
private Container container;
private ElectricMachine electricMachine;
void Awake()
{
container = GetComponent<Container>();
electricMachine = GetComponent<ElectricMachine>();
}
void Update()
{
if(electricMachine.IsPlugged)
container.Add(new Charcoal());
}
}
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
How to change variables from another script? 1 Answer
How can I access an inherited method from a separate (collided) object? 1 Answer
Calling methods on inherited classes in C# 2 Answers
Derived Class Fields 3 Answers