TExcelTAD
Home › Godot 4 with GDScript › Field Notes: Typing, Physics & Memory

Field Notes: Typing, Physics & Memory

The second set of field notes is about what happens while the game runs: how GDScript executes your code, which callback moves things, when nodes really disappear, and why changing one enemy's stats sometimes changes all of them. Every example here was run in Godot 4.7, so the behaviour shown is the engine's, not a guess.

1. Type everything

Static types in GDScript are optional, which is why so much code online has none. Add them anyway:

  • Speed. When the compiler knows the types, it emits typed instructions (for example an int + int add or a direct property access on a known class) instead of generic Variant operations that look up the type at run time. Hot loops in typed code are noticeably faster. Measure your own case with the profiler; don't trust a micro-benchmark from a forum post.
  • Errors at parse time. var hp: int = "full" fails when the script loads, not at minute 40 of a playtest.
  • Autocomplete. var body: CharacterBody2D = $Player gives you every method of CharacterBody2D in the editor. An untyped $Player gives you nothing.

Make the editor enforce it. In Project Settings > Debug > GDScript (enable Advanced Settings to see it), set Untyped Declaration to Warn or Error, and keep Unsafe Property Access, Unsafe Method Access and Unsafe Cast on Warn for a while. The script editor also colours line numbers of type-safe lines differently, so unsafe lines stand out.

Know where inference stops. := needs a value with a known type, and a value read from a Dictionary, an untyped Array or get_node() is a Variant:

gdscript
var info := Engine.get_version_info()
var major := info.major          # Parse Error: Cannot infer the type of "major" variable
var major: int = info.major      # fine: you state the type, Godot checks it at run time
var player := get_node("Player") as CharacterBody2D   # `as` gives null if the cast fails

Typed arrays protect themselves even when you reach them through an untyped variable. Adding a String to an Array[int] fails at run time with Attempted to push_back a variable of type 'String' into a TypedArray of type 'int', and the array is left unchanged. See Static Typing.

2. Movement belongs in _physics_process

_process(delta) runs once per rendered frame, so its rate follows the monitor and the machine. _physics_process(delta) runs at the fixed physics tick rate (Project Settings > Physics > Common > Physics Ticks per Second, 60 by default), with a constant delta. Bodies, move_and_slide(), raycasts and area overlaps are all updated on physics ticks. Here the physics rate is lowered to 30 while frames stay at 60:

gdscript · try it yourself
extends Node

# frames: 6
var frames := 0
var ticks := 0

func _ready():
	Engine.physics_ticks_per_second = 30

func _process(_delta):
	frames += 1

func _physics_process(delta):
	ticks += 1
	print("after ", frames, " frames: physics tick ", ticks, ", delta ", delta)
after 0 frames: physics tick 1, delta 0.03333333333333
after 2 frames: physics tick 2, delta 0.03333333333333
after 4 frames: physics tick 3, delta 0.03333333333333

Six frames, three ticks. If you moved a body in _process, it would move six times while collisions were checked three times, and the result would change with the frame rate. The rules:

  • Move CharacterBody2D/3D and read physics state in _physics_process.
  • Read one-shot input (is_action_just_pressed) in the callback that uses it; just_pressed is tracked per process frame and per physics tick separately, so it works in either.
  • Do visuals (UI, camera smoothing, particles) in _process.
  • On high refresh-rate screens, turn on Physics Interpolation (Project Settings > Physics > Common) so bodies moving at 60 ticks look smooth at 144 FPS. 2D got it in 4.3 and 3D in 4.4.

3. queue_free(), not free()

free() deletes a node immediately. queue_free() marks it for deletion at the end of the current frame, after every callback has finished. During the rest of the frame the node is still valid:

gdscript · try it yourself
extends Node

# frames: 3
var frame := 0
var bullet: Node2D

func _ready():
	bullet = Node2D.new()
	bullet.name = "Bullet"
	add_child(bullet)
	bullet.tree_exited.connect(func(): print("  (Bullet left the tree)"))

func _process(_delta):
	frame += 1
	if frame == 1:
		bullet.queue_free()
		print("frame 1: queued. valid=", is_instance_valid(bullet), " name=", bullet.name)
		bullet.position.x = 10.0   # still safe: the node is deleted at the end of the frame
		print("frame 1: x=", bullet.position.x)
	else:
		print("frame ", frame, ": valid=", is_instance_valid(bullet), " children=", get_child_count())
frame 1: queued. valid=true name=Bullet
frame 1: x=10.0
  (Bullet left the tree)
frame 2: valid=false children=0
frame 3: valid=false children=0

Why it matters: a bullet that hits two enemies in one physics step, a signal handler that frees the emitter, or a loop over get_children() that frees some of them, all crash or corrupt state with free(). With queue_free() the other callbacks this frame still see a valid node. Two follow-ups:

  • After a node might be gone, test it with is_instance_valid(node), not node != null. A freed object's variable is not null; it points to a freed instance.
  • Removing a node from the tree with remove_child() does not free it. If you never add it back or free it, it leaks (Godot prints "ObjectDB instances leaked" at exit).

Changing physics state inside a physics callback (for example disabling a CollisionShape2D in body_entered) can fail with Can't change this state while flushing queries. Use set_deferred("disabled", true) or call_deferred(...) there.

4. Resources are shared by default

Resources (.tres files, materials, shapes, your own Resource classes) are reference-counted and shared. Every enemy that loads slime_stats.tres gets the same object. Change hp on one and all of them change. duplicate() makes a copy, but only a shallow one by default: sub-resources and arrays inside are still shared.

gdscript · try it yourself
extends SceneTree

class Weapon extends Resource:
	@export var damage := 3

class Stats extends Resource:
	@export var hp := 10
	@export var weapon: Weapon
	@export var tags: Array[String] = []

func _init():
	var base := Stats.new()
	base.weapon = Weapon.new()

	var a := base               # what two enemies get when both load the same .tres
	var b := base
	a.hp -= 4
	print("shared:  a.hp=", a.hp, " b.hp=", b.hp)

	var c := base.duplicate()    # shallow: hp is copied, weapon and tags are shared
	c.hp = 99
	c.weapon.damage = 50
	c.tags.append("boss")
	print("shallow: base.hp=", base.hp, " base.weapon.damage=", base.weapon.damage, " base.tags=", base.tags)

	var d := base.duplicate(true)   # deep: sub-resources are copied too
	d.weapon.damage = 7
	print("deep:    base.weapon.damage=", base.weapon.damage, " d.weapon.damage=", d.weapon.damage)
	quit()
shared:  a.hp=6 b.hp=6
shallow: base.hp=6 base.weapon.damage=50 base.tags=["boss"]
deep:    base.weapon.damage=50 d.weapon.damage=7

Your options:

Need Do
Read-only data shared by many (item definitions, enemy templates) share it; never write to it at run time
Per-instance runtime state (current HP) keep it in a variable on the node; initialise it from the resource
A per-instance copy of a resource duplicate() in _ready(), or duplicate(true) if it holds sub-resources you change
A per-instance copy for every instanced scene tick Local to Scene (resource_local_to_scene) on the resource in the inspector

Local to Scene is the classic fix for "I changed the shader parameter on one enemy and every enemy changed colour". With it on, each instantiate() of the scene gets its own copy:

gdscript · try it yourself
extends SceneTree

func _init():
	var root := Node.new()
	var sprite := Sprite2D.new()
	sprite.name = "Sprite"
	sprite.material = CanvasItemMaterial.new()
	root.add_child(sprite)
	sprite.owner = root

	var scene := PackedScene.new()
	scene.pack(root)
	var e1 := scene.instantiate()
	var e2 := scene.instantiate()
	print("default: same material? ", e1.get_node("Sprite").material == e2.get_node("Sprite").material)

	sprite.material.resource_local_to_scene = true
	scene.pack(root)
	var e3 := scene.instantiate()
	var e4 := scene.instantiate()
	print("local to scene: same material? ", e3.get_node("Sprite").material == e4.get_node("Sprite").material)

	for n in [root, e1, e2, e3, e4]:
		n.free()
	quit()
default: same material? true
local to scene: same material? false

Note: For shaders there is a cheaper option than unique materials: per-instance uniforms (instance uniform in spatial shaders, set with set_instance_shader_parameter). See The Godot Shading Language.

5. Smaller habits that pay off

  • Cache node references with @onready var sprite: Sprite2D = $Sprite instead of calling get_node() every frame.
  • Disable what you don't need: set_process(false) / set_physics_process(false) on idle nodes; a VisibleOnScreenNotifier2D can turn off enemies off screen.
  • Pool or reuse only after the profiler shows instancing cost. Godot's instantiate() is cheap for small scenes.
  • Don't poll the tree with get_nodes_in_group() every frame in hot code; keep a list and update it with signals.
  • Strings in hot paths ("%s" % x, str()) allocate; use StringName constants (&"jump") for action and group names you compare often.

Test yourself

A node calls queue_free() on itself in _physics_process. When is it deleted?

  1. Immediately, the next line crashes
  2. At the end of the current frame, after the other callbacks have run
  3. When the scene is changed
  4. Never, until free() is also called

Ten enemies load the same stats.tres and one of them does stats.hp -= 5. What happens?

  1. Only that enemy loses HP
  2. All ten see the lower HP, because the resource is shared
  3. Godot raises an error
  4. The .tres file on disk is changed automatically

var copy := stats.duplicate() and then copy.weapon.damage = 50. Does the original's weapon change?

  1. No, duplicate() always copies everything
  2. Yes, the default duplicate is shallow, so the sub-resource is shared; use duplicate(true)
  3. Only if the weapon is local to scene
  4. It depends on the frame rate