Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Export and Optimization

Optimizing 2D and 3D Scenes

Speed up a Godot 4 game: draw calls, batching, texture atlases, MultiMeshInstance, visibility ranges and LOD, occlusion culling, object pooling, spatial hashing and GDScript tips, with Python stand-ins.

After profiling tells you where the time goes, you fix it. Most Godot performance problems fall into four buckets: too many things drawn, too many things simulated, too much work in scripts, and too much memory churn. This lesson gives a practical toolbox for each.

Godot cannot run on this site, so engine code is read-only and the runnable blocks are Python stand-ins for the algorithms. Always profile before and after: an optimization that does not move the numbers is only added complexity.

Reduce what is drawn

Each distinct combination of mesh, material and state can cost a draw call, a CPU-side command to the GPU. Thousands of draw calls make a CPU-bound renderer crawl.

  • 2D: put sprites in one texture atlas so they share a texture and can be batched. Use TileMapLayer instead of thousands of Sprite2D nodes. Set CanvasItem.visible = false or use VisibleOnScreenNotifier2D to stop off-screen enemies from processing.
  • 3D: reuse meshes and materials (the same resource), merge static meshes, and use MultiMeshInstance3D for many copies of one mesh (grass, trees, bullets): it draws all the instances in one call.
  • Cull what cannot be seen: Godot already does frustum culling. Add occlusion culling (an OccluderInstance3D baked from walls) for dense interiors, and visibility ranges (visibility_range_end) to hide small details far away.
  • LOD (level of detail): Godot auto-generates lower-detail meshes on import (Generate LODs); lod_bias tunes when they switch. Use HLOD with visibility ranges for whole groups.
  • Lower GPU cost: reduce shadow map sizes and distance, turn off SSAO/SSR/glow on weak devices, avoid large transparent overlapping areas (overdraw), and lower the 3D render scale (Viewport.scaling_3d_scale or FSR).
GDSCRIPT
extends MultiMeshInstance3D

func _ready() -> void:
	var mm := MultiMesh.new()
	mm.transform_format = MultiMesh.TRANSFORM_3D
	mm.mesh = preload("res://art/grass_blade.tres")
	mm.instance_count = 5000
	for i in mm.instance_count:
		var pos := Vector3(randf_range(-50, 50), 0, randf_range(-50, 50))
		mm.set_instance_transform(i, Transform3D(Basis.IDENTITY, pos))
	multimesh = mm
Python Stand-in (Python, not Godot): draw calls with and without batching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reduce what is simulated

  • Disable nodes you do not need: set_process(false), set_physics_process(false) or process_mode = Node.PROCESS_MODE_DISABLED for off-screen or sleeping enemies. VisibleOnScreenEnabler2D does this automatically.
  • Fewer physics bodies, simpler shapes: a capsule beats a polygon. Make bodies sleep when still (can_sleep). Use Area queries sparingly and set collision masks tightly so objects ignore each other (see collision layers).
  • Do not run expensive logic every frame: use a Timer or a counter so AI "thinks" 5 times per second, not 60.
  • Spread the load: update 1/4 of the enemies each frame (round-robin).
  • Avoid O(nยฒ): checking every enemy against every other enemy is slow. Use a spatial hash or physics areas.
Python Stand-in (Python, not Godot): a spatial hash makes neighbour search cheap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both methods find the same pairs, but the grid tests each point only against its neighbouring cells. With 2000 points the brute-force method does about 2 million tests.

Cheaper scripts

GDScript is fast enough for most games if you avoid waste:

  • Use static typing (var speed: float, func move(dir: Vector2) -> void): typed code runs faster because the engine can use specialized instructions.
  • Cache node lookups with @onready var sprite := $Sprite2D instead of calling get_node or $ every frame.
  • Compare squared distances and avoid sqrt, normalized() and allocations inside hot loops.
  • Use _physics_process only for physics, _process for visuals, and neither when a signal can notify you instead of polling.
  • Prefer packed arrays (PackedVector2Array, PackedFloat32Array) for large numeric data.
  • Use the right data structure: a Dictionary lookup is O(1); searching an Array with find() is O(n).
  • For heavy numeric work, use C# or GDExtension (C++/Rust) for just the hot function.
  • Move long calculations to a WorkerThreadPool task (never touch scene tree nodes from threads without call_deferred).

Object pooling: stop creating and freeing

Instantiating a scene (PackedScene.instantiate()) and calling queue_free() hundreds of times per second causes hitches (allocations and garbage). A pool creates N objects once, hides them, and reuses them.

GDSCRIPT
class_name BulletPool
extends Node

@export var bullet_scene: PackedScene
@export var size := 64
var free_bullets: Array[Node2D] = []

func _ready() -> void:
	for i in size:
		var b := bullet_scene.instantiate() as Node2D
		b.visible = false
		b.process_mode = Node.PROCESS_MODE_DISABLED
		add_child(b)
		free_bullets.append(b)

func spawn(pos: Vector2, dir: Vector2) -> Node2D:
	if free_bullets.is_empty():
		return null                           # pool exhausted: skip or grow
	var b: Node2D = free_bullets.pop_back()
	b.global_position = pos
	b.visible = true
	b.process_mode = Node.PROCESS_MODE_INHERIT
	return b

func release(b: Node2D) -> void:
	b.visible = false
	b.process_mode = Node.PROCESS_MODE_DISABLED
	free_bullets.append(b)
Python Stand-in (Python, not Godot): allocation count with and without a pool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Memory

Free what you do not use: call queue_free() on nodes you remove (removing from the tree with remove_child does not delete them, and forgotten nodes appear as orphan nodes in the Monitors). Use preload for small always-needed resources and ResourceLoader.load_threaded_request() for levels so loading does not freeze the game. Compress textures and watch Video RAM in the debugger.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which node draws thousands of copies of one mesh in a single draw call?

    A MultiMesh stores many instance transforms and is drawn as one batch.
  2. 2. How can you cut script cost without changing behavior?

    Typed code runs faster, and cached references avoid repeated lookups.
  3. 3. What problem does object pooling solve?

    A pool reuses objects so instantiate and queue_free are not called in hot paths.
  4. 4. Why compare squared distances?

    If a squared <= b squared (for non-negative values) then a <= b, so compare with r*r and skip sqrt.

Summary

  • Cut draw calls with atlases, shared materials, MultiMesh, culling and LOD.
  • Reduce simulation: disable idle nodes, simplify shapes, spread work, avoid O(nยฒ) with spatial hashing.
  • Type your GDScript, cache nodes, compare squared distances and use packed arrays.
  • Pool frequently spawned objects; free what you no longer use; always re-measure.

Next: Project: A Platformer Level