In my spare time, I enjoy browsing through GitHub and reading other people’s code to see how much I can understand. Recently, I came across the official Godot demo projects, specifically the multiplayer pong demo.
I’m having trouble understanding the concept of deferred calls. I get what they are doing, but I’m not clear on when I should use them. My understanding is that deferred calls execute a method during “idle time,” when the CPU isn’t processing anything else, making it safe to do operations that might interfere with other code, like modifying the scene tree.
Here’s the relevant code from the project:
#region Network callbacks from SceneTree
# Callback from SceneTree.
func _player_connected(_id: int) -> void:
# Someone connected, start the game!
var pong: Node2D = load("res://pong.tscn").instantiate()
# Connect deferred so we can safely erase it from the callback.
pong.game_finished.connect(_end_game, CONNECT_DEFERRED)
get_tree().get_root().add_child(pong)
hide()
func _server_disconnected() -> void:
_end_game("Server disconnected.")
#endregion
#region Game creation methods
func _end_game(with_error: String = "") -> void:
if has_node("/root/Pong"):
# Erase immediately, otherwise network might show
# errors (this is why we connected deferred above).
get_node(^"/root/Pong").free()
show()
I’m particularly confused about the comment, “Connect deferred so we can safely erase it from the callback.” From what I understand, we are using the multiplayer API and hooking our methods via signals, which act as callbacks. I need help understanding what it means to “erase from the callback” and what does “safely erase” imply? What are the consequences of doing it non-safely? I also didn’t get the “erase immediately” part in _end_game method.
Can someone clarify this for me?