An instance is a reproduction of a template. In the real world, if you have plans to build a house, you can build many houses based on the same plans. Each house would be an "instance" of the plans.
In programming, similarly, you can create as many objects as you want from a class or a scene. We say that each object is an instance of the class or scene it was created from.
In Godot, there are two mechanisms to create instances:
- We use the
.new()
function for class instances.
- We use the
.instantiate()
function for scene instances.
For example, to create a Node2D
node instance in code, you would write:
var my_node := Node2D.new()
To create a new Image
resource instance, you would write:
var my_image := Image.new()
Godot creates a fresh reproduction of the class with default properties in both cases.
To instantiate a scene from a loaded PackedScene
resource, we use the packed scene's .instantiate()
method.
For example, to create a new instance of a particular scene, you would write:
var packed_scene_resource := preload("my_scene.tscn")
var scene_instance = packed_scene_resource.instantiate()
var scene_instance = preload("my_scene.tscn").instantiate()
Why don't we use `.new()` for scenes?The .new()
method creates a new class instance. A loaded PackedScene
resource is not a class. It's an object and an instance of the PackedScene
class. So, when you load a scene in code, the loaded resource does not have a .new()
method.The PackedScene
class itself has a .new()
method, but calling it creates an empty scene template, not an instance of a scene file. The following code would create an empty scene template:var my_scene := PackedScene.new()
See Also
Related terms in the Glossary