As far as I am aware there are two main ways to instantiate class in gdscript 2.0.
- Preload/load class with script and create instance:
var some_class = preload("res://SomeClass.gd") ... var instance = some_class.new(...args)
- Use class_name
# in SomeClass.gd class_name some_class extends Object # in place where class instantiated var instance = some_class.new(...args)
Which way to create new instance of class is preferred? What are differences between two methods? Is there any reason to avoid just using
You can use
class_name everywhere in your game code.
The differences I’m aware of are:
preloadcan take a relative path.
class_nameclasses are always available.
class_namepollutes the global scope.
preload is better for reusable components. Stuff that you want to be able to take from one project to another, and without worry they will conflict with something. In other words: addons.
Thus: default to
class_name unless you have a reason not to (and that is probably when writing addons or editor plugins).