Scripting (continued)

Processing

Several actions in Godot are triggered by callbacks or virtual functions, so there is no need to write code that runs all the time.

However, it is still common to need a script to be processed on every frame. There are two types of processing: idle processing and physics processing.

Idle processing is activated when the method Node._process() is found in a script. It can be turned off and on with the Node.set_process() function.

This method will be called every time a frame is drawn:

GDScript

C#

  1. func _process(delta):
  2. # Do something...
  3. pass
  1. public override void _Process(float delta)
  2. {
  3. // Do something...
  4. }

It’s important to bear in mind that the frequency with which _process() will be called depends on how many frames per second (FPS) your application is running at. This rate can vary over time and devices.

To help manage this variability, the delta parameter contains the time elapsed in seconds as a floating-point number since the previous call to _process().

This parameter can be used to make sure things always take the same amount of time, regardless of the game’s FPS.

For example, movement is often multiplied with a time delta to make movement speed both constant and independent of the frame rate.

Physics processing with _physics_process() is similar, but it should be used for processes that must happen before each physics step, such as controlling a character. It always runs before a physics step and it is called at fixed time intervals: 60 times per second by default. You can change the interval from the Project Settings, under Physics -> Common -> Physics Fps.

The function _process(), however, is not synced with physics. Its frame rate is not constant and is dependent on hardware and game optimization. Its execution is done after the physics step on single-threaded games.

A simple way to see the _process() function at work is to create a scene with a single Label node, with the following script:

GDScript

C#

  1. extends Label
  2. var accum = 0
  3. func _process(delta):
  4. accum += delta
  5. text = str(accum) # 'text' is a built-in label property.
  1. public class CustomLabel : Label
  2. {
  3. private float _accum;
  4. public override void _Process(float delta)
  5. {
  6. _accum += delta;
  7. Text = _accum.ToString(); // 'Text' is a built-in label property.
  8. }
  9. }

Which will show a counter increasing each frame.

Groups

Groups in Godot work like tags you might have come across in other software. A node can be added to as many groups as desired. This is a useful feature for organizing large scenes. There are two ways to add nodes to groups. The first is from the UI, using the Groups button under the Node panel:

../../_images/groups_in_nodes.png

And the second way is from code. The following script would add the current node to the enemies group as soon as it appeared in the scene tree.

GDScript

C#

  1. func _ready():
  2. add_to_group("enemies")
  1. public override void _Ready()
  2. {
  3. base._Ready();
  4. AddToGroup("enemies");
  5. }

This way, if the player is discovered sneaking into a secret base, all enemies can be notified about its alarm sounding by using SceneTree.call_group():

GDScript

C#

  1. func _on_discovered(): # This is a purely illustrative function.
  2. get_tree().call_group("enemies", "player_was_discovered")
  1. public void _OnDiscovered() // This is a purely illustrative function.
  2. {
  3. GetTree().CallGroup("enemies", "player_was_discovered");
  4. }

The above code calls the function player_was_discovered on every member of the group enemies.

It is also possible to get the full list of enemies nodes by calling SceneTree.get_nodes_in_group():

GDScript

C#

  1. var enemies = get_tree().get_nodes_in_group("enemies")
  1. var enemies = GetTree().GetNodesInGroup("enemies");

The SceneTree class provides many useful methods, like interacting with scenes, their node hierarchy and groups of nodes. It allows you to easily switch scenes or reload them, to quit the game or pause and unpause it. It even comes with interesting signals. So check it out if you have some time!

Notifications

Godot has a system of notifications. These are usually not needed for scripting, as it’s too low-level and virtual functions are provided for most of them. It’s just good to know they exist. For example, you may add an Object._notification() function in your script:

GDScript

C#

  1. func _notification(what):
  2. match what:
  3. NOTIFICATION_READY:
  4. print("This is the same as overriding _ready()...")
  5. NOTIFICATION_PROCESS:
  6. print("This is the same as overriding _process()...")
  1. public override void _Notification(int what)
  2. {
  3. base._Notification(what);
  4. switch (what)
  5. {
  6. case NotificationReady:
  7. GD.Print("This is the same as overriding _Ready()...");
  8. break;
  9. case NotificationProcess:
  10. var delta = GetProcessDeltaTime();
  11. GD.Print("This is the same as overriding _Process()...");
  12. break;
  13. }
  14. }

The documentation of each class in the Class Reference shows the notifications it can receive. However, in most cases GDScript provides simpler overridable functions.

Overridable functions

Such overridable functions, which are described as follows, can be applied to nodes:

GDScript

C#

  1. func _enter_tree():
  2. # When the node enters the Scene Tree, it becomes active
  3. # and this function is called. Children nodes have not entered
  4. # the active scene yet. In general, it's better to use _ready()
  5. # for most cases.
  6. pass
  7. func _ready():
  8. # This function is called after _enter_tree, but it ensures
  9. # that all children nodes have also entered the Scene Tree,
  10. # and became active.
  11. pass
  12. func _exit_tree():
  13. # When the node exits the Scene Tree, this function is called.
  14. # Children nodes have all exited the Scene Tree at this point
  15. # and all became inactive.
  16. pass
  17. func _process(delta):
  18. # This function is called every frame.
  19. pass
  20. func _physics_process(delta):
  21. # This is called every physics frame.
  22. pass
  1. public override void _EnterTree()
  2. {
  3. // When the node enters the Scene Tree, it becomes active
  4. // and this function is called. Children nodes have not entered
  5. // the active scene yet. In general, it's better to use _ready()
  6. // for most cases.
  7. base._EnterTree();
  8. }
  9. public override void _Ready()
  10. {
  11. // This function is called after _enter_tree, but it ensures
  12. // that all children nodes have also entered the Scene Tree,
  13. // and became active.
  14. base._Ready();
  15. }
  16. public override void _ExitTree()
  17. {
  18. // When the node exits the Scene Tree, this function is called.
  19. // Children nodes have all exited the Scene Tree at this point
  20. // and all became inactive.
  21. base._ExitTree();
  22. }
  23. public override void _Process(float delta)
  24. {
  25. // This function is called every frame.
  26. base._Process(delta);
  27. }
  28. public override void _PhysicsProcess(float delta)
  29. {
  30. // This is called every physics frame.
  31. base._PhysicsProcess(delta);
  32. }

As mentioned before, it’s better to use these functions instead of the notification system.

Creating nodes

To create a node from code, call the .new() method, like for any other class-based datatype. For example:

GDScript

C#

  1. var s
  2. func _ready():
  3. s = Sprite.new() # Create a new sprite!
  4. add_child(s) # Add it as a child of this node.
  1. private Sprite _sprite;
  2. public override void _Ready()
  3. {
  4. base._Ready();
  5. _sprite = new Sprite(); // Create a new sprite!
  6. AddChild(_sprite); // Add it as a child of this node.
  7. }

To delete a node, be it inside or outside the scene, free() must be used:

GDScript

C#

  1. func _someaction():
  2. s.free() # Immediately removes the node from the scene and frees it.
  1. public void _SomeAction()
  2. {
  3. _sprite.Free(); // Immediately removes the node from the scene and frees it.
  4. }

When a node is freed, it also frees all its child nodes. Because of this, manually deleting nodes is much simpler than it appears. Free the base node and everything else in the subtree goes away with it.

A situation might occur where we want to delete a node that is currently “blocked”, because it is emitting a signal or calling a function. This will crash the game. Running Godot with the debugger will often catch this case and warn you about it.

The safest way to delete a node is by using Node.queue_free(). This erases the node safely during idle.

GDScript

C#

  1. func _someaction():
  2. s.queue_free() # Removes the node from the scene and frees it when it becomes safe to do so.
  1. public void _SomeAction()
  2. {
  3. _sprite.QueueFree(); // Removes the node from the scene and frees it when it becomes safe to do so.
  4. }

Instancing scenes

Instancing a scene from code is done in two steps. The first one is to load the scene from your hard drive:

GDScript

C#

  1. var scene = load("res://myscene.tscn") # Will load when the script is instanced.
  1. var scene = GD.Load<PackedScene>("res://myscene.tscn"); // Will load when the script is instanced.

Preloading it can be more convenient, as it happens at parse time (GDScript only):

GDScript

  1. var scene = preload("res://myscene.tscn") # Will load when parsing the script.

But scene is not yet a node. It’s packed in a special resource called PackedScene. To create the actual node, the function PackedScene.instance() must be called. This will return the tree of nodes that can be added to the active scene:

GDScript

C#

  1. var node = scene.instance()
  2. add_child(node)
  1. var node = scene.Instance();
  2. AddChild(node);

The advantage of this two-step process is that a packed scene may be kept loaded and ready to use so that you can create as many instances as desired. This is especially useful to quickly instance several enemies, bullets, and other entities in the active scene.

Register scripts as classes

Godot has a “Script Class” feature to register individual scripts with the Editor. By default, you can only access unnamed scripts by loading the file directly.

You can name a script and register it as a type in the editor with the class_name keyword followed by the class’s name. You may add a comma and an optional path to an image to use as an icon. You will then find your new type in the Node or Resource creation dialog.

GDScript

  1. extends Node
  2. # Declare the class name here
  3. class_name ScriptName, "res://path/to/optional/icon.svg"
  4. func _ready():
  5. var this = ScriptName # reference to the script
  6. var cppNode = MyCppNode.new() # new instance of a class named MyCppNode
  7. cppNode.queue_free()

../../_images/script_class_nativescript_example.png

Warning

In Godot 3.1:

  • Only GDScript and NativeScript, i.e., C++ and other GDNative-powered languages, can register scripts.

  • Only GDScript creates global variables for each named script.