Memory Management
Game programming is part coding and part of memory management.
Understanding memory management can help you understand where problems are happening with your game. Such issues may include lag or random game freezes.
Reference Class
In Godot GDScript, all classes that don’t define an inheritance through the extends
keyword
will inherit from the reference class by default.
# Omitting the extends keyword is the same as the following
extends Reference
The Reference
class is the base class for any game object that keeps a reference count.
Reference counting is a memory management technique.
This means that the class will release itself from memory when it is no longer used.
This works because an object will be released from memory when the reference count is 0
.
Object Class
If you would like to have a game object stay in memory even when it is no longer being used,
you will have to inherit from the Object
class.
To free a game object which inherits from the object class from memory, you will have
to call the free
method.
Many of Godot’s built-in Classes inherit from the Object class. This includes the Node class and the Node2D class.
Many problems beginners have when programming with Godot is freeing Nodes from memory.
# An example of freeing a Sprite Node from memory
# Sprite Node ultimately inherits from Object class
extends Sprite
class_name MainCharacter
_exit_tree():
free() # unsafe
Another way of deleting from memory:
# An example of freeing a Sprite Node from memory
# Sprite Node ultimately inherits from Object class
extends Sprite
class_name MainCharacter
_exit_tree():
queue_free() # safe