In Godot, you call .new() on a class to create a new instance. This invokes the _init() method, which is the constructor of the class.
Often, you might be interested in passing different arguments to the constructor. A good way of handling this is to make your own custom constructors. For example, suppose you have an Item class like so:
class_name Item extendsArea3Dvar name :=""var weight :=1var cost :=10func_init(p_name:String, p_weight:float, p_cost:int)->void:
name = p_name
cost = p_cost
weight = p_weight
If most items in your game have a weight of 1 and a cost of 10, you can create a convenience method to create items with default values:
You're not limited to new()! This frees you from having to remember the order of arguments when creating instances, and also allows you to keep _init() clean and simple.
Become an Indie Gamedev with GDQuest!in GDSchool
Don't stop here. Step-by-step tutorials are fun but they only take you so far.
Try one of our proven study programs to become an independent Gamedev truly capable of realizing the games you’ve always wanted to make.