Dev Day 72: Class Inheritance in Unity3D

Objective: Create two custom classes and have one custom class inherit the properties of the other custom class.

Step 1: In Unity, within the Hierarchy window, create an Empty GameObject named Item_Database. In the Project window, create three C# Scripts called Item, Weapon, and ItemDatabase. Then drag the ItemDatabase script onto the Item_Database GameObject.

Step 2: In the Item script, remove the MonoBheaviour properties and add [System.Serializeable]. Then create protected variables for the common traits for all items within a game and utilize [SerializeField] for all variables. Ex: Name, ID, Weight, etc. Using protected variables allows scripts that are inheriting custom class scripts access to the information within the inherited scripts but are private from all other scripts.

Step 3: Within the Weapon script, replace MonoBehaviour with the Item class, which will inherit the properties of the Item class, and create protected variables for attributes that are only specific to weapons.

Step 4: Within the ItemDatabase script, create a public variable of type Item called torch and have it equal to new Item(). Then create a public variable of type weapon called shortSword and have that equal to new Weapon().

Save the scripts, go back into Unity, and within the Item Database (Script) component in the Inspector window for the Item_Database GameObject, the details for each item will be listed with the Short Sword utilizing both the Item class properties (Red) and the Weapon class properties (Green).

Unity Developer