Classes in Unity (Part 2/3): Class Inheritance
In the previous blog post, we talked about the differences between MonoBehaviour and custom classes and how to create a custom class in Unity. In today’s blog post, let’s talk about Class Inheritance and how you can use it to organize your code better.
What is Inheritance?
In object-oriented programming (OOP), inheritance enables new objects to inherit the properties of existing objects. For example, if you have a script called “Item” and use it to store information about items in your game, such as ID, name, description, etc. However, there are items that are very different from one another, like a loaf of bread and a sword, which have distinct uses and behaviors and therefore shouldn’t be stored in the same script. By utilizing class inheritance, you can create a sword script that inherits properties from the item script.
How to use Inheritance in Unity?
Now, we know why we should use Inheritance in Unity, let’s create a simple example for this. I’ve created a script for all items in the game with a custom class that has four properties including name, id, description, and icon.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item
{
public string name;
public int id;
public string description;
public Sprite icon;
}Now, I’m gonna create two more custom scripts that will inherit these properties from the Item script.
Get Simon Pham’s stories in your inbox
Join Medium for free to get updates from this writer.
The first one is a script for consumables:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Consumable : Item
{
public int addedHealth;
public bool poison;
}And the second one is a script for weapons.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Weapon : Item
{
public int damage;
public int cost;
public int levelRequired;
}You might have noticed that I’ve replaced the “MonoBehaviour” namespace with the “Item” namespace in both of the scripts.
Next, let’s create another script that we can use to create new items — ItemDB, and I’ll attach it to a GameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemDB : MonoBehaviour
{
public Weapon sword = new Weapon();
public Consumable bread = new Consumable();
public Item goldCoin = new Item();
}I’ve created three different items: a sword, a loaf of bread, and a gold coin. And in the editor, you can see that the sword and bread both inherit properties from the Item script while still having their own unique properties.









