Traditionally, inheritance is leveraged within object-oriented programming to reuse code without rewriting it. In Unity, however, it’s better to use a composition-based approach.
At a high level, components in Unity are just C# scripts that can be added onto a GameObject; they can be designed and implemented in many ways. Building up game features using sub-components (rather than inheriting from an object) is usually more efficient and easier to maintain. This is what makes it a “component-based” design.
Thinking About Component Architecture up Front
It’s helpful to spend time designing the component architecture of your game because it can reduce overhead time in the long run. Let’s say we want to add a weapon system into a game for players/enemies; we want a sword, a crossbow, and a slingshot.
Using inheritance, you could create a tree for both ranged and non-ranged weapons. You could say that the crossbow and slingshot inherit some of their functionality from the ranged branch since they fire projectiles. But do we really need trees here? You could say that a sword is a ranged weapon, too (with a very low range). In this example, I only have three weapons, but if there were many more, developers could potentially be stuck maintaining several branches of scripts (or a handful of very large ones) for common behavior used across the system.
This is where components save the day! If we divide up the functionality of what any generic weapon can do into sub-components, this problem can be simplified.
Let’s say that any weapon will have a component for damage, range, and projectiles (optional). Using Unity’s UI, you could create a weapon by dragging these components onto any GameObject and customizing the values of each one. Then, if the way projectiles are handled changes further into development, all you need to do is change one script, and all your weapons’ functionalities will be updated instead of just those defined at one level of a tree.
Examples from a Game I Worked On
In these screenshots, I have two examples of component-based systems for both NPCs/enemies and weapons. Each “(Script)” is its own component. Using this design, several components make up one enemy/weapon, and each one can be reused to create a unique GameObject down the line simply by modifying the input values.
Weapon Component System
NPC / Enemy Component System