Are you intrigued by the vast capabilities of GDScript and the nifty tricks that can simplify your coding life? Then you are in for a treat! Buckle up and stay tuned to this comprehensive beginner-friendly tutorial on “GDScript inheritance”. Diving into the realms of inheritance in GDScript will surely add an exciting layer to your game development journey.
Table of contents
What Is GDScript Inheritance?
GDScript Inheritance is a powerful feature that allows a GDScript class to ‘inherit’ properties and methods from another. A class that inherits from another is referred to as a ‘subclass’, while the class being inherited from is known as the ‘superclass’.
The Purpose of GDScript Inheritance
The main purpose of inheritance is to promote code reusability and organization. By taking advantage of inheritance, you can create a base class (a superclass) that defines common behaviours, and then create subclasses that specialize these behaviours without rewriting common code.
Why Should I Learn GDScript Inheritance?
Mastering the concept of inheritance can drastically improve your programming abilities. For game developers, harnessing inheritance can enable complex game behaviour with less code. It is an essential part of your toolkit as a game developer particularly if you’re using Godot Engine with GDScript.
Implementing Basic Inheritance in GDScript
Let’s start with a simple example to demonstrate how GDScript Inheritance works.
Imagine we have a base class, a ‘Vehicle’. This class might have a method that defines how the vehicle moves.
class Vehicle: var speed = 0 func move(): print("Moving at speed: ", speed)
Now, we could create a subclass, ‘Car’, that inherits from the superclass, ‘Vehicle’. This ‘Car’ class might modify the ‘move’ function to consider its specific behaviours.
class Car extends Vehicle: func move(): speed += 10 print("Car is moving at speed: ", speed)
GDScript: Overriding Methods and Calling Superclass Methods
Now, let’s consider a scenario where we want our Car subclass to execute a few extra instructions in the ‘move’ method, in addition to what it has inherited from Vehicle superclass.
class Car extends Vehicle: func move(): speed += 10 .move()
In the above code, we are overriding the ‘move’ method but we also want to execute the ‘move’ method from the Vehicle superclass. We used the dot operator (.) to call the superclass method.
Note: Remember, if a subclass is overriding a method and still wants to call the superclass method, the superclass method MUST be called explicitly or else it won’t be executed.
GDScript Inheritance: Nested Inheritance
GDScript allows for multiple levels of subclasses to be created. This can be referred to as ‘nested’ or ‘multilevel’ inheritance.
Consider a new class ‘SportsCar’ which is a subclass of ‘Car’ and of course, an indirect subclass of ‘Vehicle’.
class SportsCar extends Car: func move(): speed += 20 .move()
In the above code, SportsCar is inheriting from Car, which is itself a subclass of Vehicle. Hence, SportsCar is indirectly inheriting from Vehicle.
Inheritance is a powerful concept that enables you to create complex game mechanics using simple, organized and reusable code. Remember, practice is the key to master the art of writing clean and efficient GDScript code. Don’t be afraid to experiment with designing different subclasses and methods!
More Complex Examples of GDScript Inheritance
Now that we have basic understanding of inheritance in GDScript, let’s dive a bit deeper and explore more complex scenarios and how we can leverage the power of inheritance to overcome them.
Calling Superclass’s Constructor
In GDScript, the ‘constructor’ of a class is a special method named `_init()`. It helps you initialize variables when an object is created. This automatic function call can be useful when setting up your subclasses. Let’s see this in action:
class Vehicle: var color = "" func _init(color): self.color = color class Car extends Vehicle: var type = "car" func _init(color): .(color)
As seen above, in Vehicle we have defined a constructor that takes ‘color’ as a parameter. In the Car subclass, we want to keep this behavior, so we call the superclass’s constructor using the dot operator (.).
Method Chaining in Inheritance
Method chaining is a technique where the calls of several methods are chained together. This can be useful in cases of multiple subclassing levels. An example:
class Vehicle: func move(): print("Vehicle is moving...") class Car extends Vehicle: func move(): print("Car is ready..") .move() class SportsCar extends Car: func move(): print("Sports car is ready..") .move()
In the above example, when we call ‘move’ method of the ‘SportsCar’ class, it prints “Sports car is ready..”, calls ‘move’ of class ‘Car’ which prints “Car is ready..” and then calls its own superclass method from ‘Vehicle’ that prints “Vehicle is moving…”.
Inheritance Between Different Scripts
In GDScript, you can extend a class from a different script as well. A common practice is to keep base classes in a separate script. Here’s how you can do it:
# In Vehicle.gd class Vehicle: func move(): print("Moving at speed: ", speed) # In Car.gd extends "Vehicle.gd"
The ‘extends’ keyword is followed by the path to the script from which we want to inherit.
We have only scratched the surface of inheritance in GDScript. As you start building complex games, you will inevitably face numerous scenarios where the innate power of inheritance can come in handy. Therefore, we encourage you to explore more, experiment with different use-cases, and cement your understanding of this powerful concept.
The ‘is’ Keyword in GDScript Inheritance
The ‘is’ keyword grants the ability to check if a class instance is of a certain type or not, or if it inherits from a certain type. This keyword becomes considerably useful whilst dealing with inheritance.
class Vehicle: func getType(): print("Vehicle") class Car extends Vehicle: func getType(): print("Car") var car = Car.new() print(car is Car) # Prints true print(car is Vehicle) # Prints true
As we can see, the ‘is’ keyword can confirm that our ‘car’ instance is of both types; Car and Vehicle.
Exporting Variables in GDScript Inheritance
Exporting variables is a great way to expose class variables in the Godot editor. The exported variables can be accessed and modified from the Inspector window for ease. Let’s see how to do it.
class Car extends Vehicle: export var brand = ""
By adding the ‘export’ keyword, GDScript exposes the ‘brand’ variable of the ‘Car’ class to the Godot editor.
How to Use ‘onready’ Keyword in Subclasses
The ‘onready’ keyword is another powerful tool in GDScript. It allows you to assign a value to a variable only when the node and its children nodes are fully loaded. Here’s an example:
class Car extends Vehicle: onready var is_ready = true
The keyword ‘onready’ tells Godot to set ‘is_ready’ to true when both ‘Vehicle’ (superclass) and ‘Car’ (subclass) are ready.
Mixing Between Different Inheritance Concepts
GDScript’s inheritance enables you to mix and match from different concepts to best fit your game’s need. Let’s explore a more complicated scenario:
# In Vehicle.gd class Vehicle: export var speed = 0 # In Car.gd extends "Vehicle.gd" var color = "" func _init(color): self.color = color func move(): speed += 10 print("Car of color ", color, " moving at speed: ", speed) onready var is_ready = true
In this example, we’re meshing exports, initializers, and onready together to build upon our Car’s functionality.
The more you utilize these tools together, the more versed you’ll become at creating complex behavior. Remember, the key to mastering game development is to experiment and apply creatively!
Where To Go Next?
Having grasped the rudiments and intricacies of GDScript inheritance, you’re now armed with a powerful tool that can significantly streamline and enhance your game development journey. However, don’t rest just yet! There is still a vast expanse of knowledge waiting to be unearthed, and we’re here to guide you every step of the way.
To delve deeper into the thrilling world of game development, we invite you to explore our Godot Game Development Mini-Degree. This comprehensive program provides a broad spectrum of knowledge that ranges from creating 2D and 3D assets, mastering GDScript, setting up complex gameplay control flows, and even different game mechanics like RPG, RTS, survival, and platformer. Crafted by our experienced game developers, these courses are delivered in an easily digestible format for both absolute beginners and experienced coders.
Alternatively, you can explore a wider range of related topics in our extensive Godot Courses. Regardless of where your game development passion lies, we at Zenva are dedicated to providing you with high-quality educational content to give you the skills you need to excel in the industry.
Dive headfirst into the exciting world of game development with GDScript and supercharge your programming prowess. Knowledge of inheritance and its intricacies is an indispensable part of every game developer’s toolkit. As you keep exploring and experimenting with GDScript, you’ll be unlocking new levels of creativity, enabling you to solve complex problems and create engaging gaming experiences for your audience.
We at Zenva, are inspired by the passion of learners like you. We are committed to providing high-quality educational content that caters to all levels of learning, from beginners to seasoned professionals. Our Godot Game Development Mini-Degree is a testament to this commitment and a perfect next step in your learning journey. Let’s embark on this journey together and bring your game development dreams to life!
FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.