Issue
This Content is from Stack Overflow. Question asked by iwek
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 export_class
everywhere?
Solution
You can use class_name
everywhere in your game code.
The differences I’m aware of are:
preload
can take a relative path.class_name
classes are always available.class_name
pollutes the global scope.
Thus, 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).
This Question was asked in StackOverflow by iwek and Answered by Theraot It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.