Pitfalls: GDScript & UI
Curated traps, subtle engine behaviors, and invariants for Godot 4.7+ and GDScript development.
Theming, Styling & Colors
- Pressed-state text color ignores
font_color: A toggle-modeButtonresolves text fromfont_pressed_color, which falls back to the theme default and silently ignoresfont_color. Use a type variation role (e.g.,UiTheme.ACCENT_BUTTON), which definesfont_color,font_hover_color,font_pressed_color, andfont_focus_colortogether in the theme. - ScrollBar thickness is derived from content margins: Godot derives
ScrollBarthickness from the track stylebox’s content margins plus padding constants (VScrollBar.padding_left/padding_right), while the grabber stylebox margins only determine thumb minimum length. An empty track (StyleBoxEmpty) creates a 0 px bar with no column reserved. Geometry is theme-owned (UiTokens.SCROLLBAR_THICKNESS/SCROLLBAR_INSET/SCROLLBAR_MIN_THUMB). - Embedded Window frame uses default theme:
Window/embedded_borderandembedded_unfocused_borderhave no effect in Godot 4.7.2. AnAcceptDialoglays out every direct child Control over the same content rect (requiring a single rootVBoxContainer), and its internaldialog_textkeeps rendering until hidden.AppDialogbuilds borderless modals with custom headers. - A per-surface
modulateis not a translucent window:Window.transparent/transparent_bgplus aWorkspace.modulatealpha makes every stacked surface blend again instead of fading the finished window - the terminal’s row backgrounds, its ground and the window ground compounded to framebuffer alpha 0.992 at a 70 % setting (measured 2026-11-20 on 4.7.2). A whole-window alpha is one post-pass:godot/shaders/window_opacity.gdshadersamples aBackBufferCopyplaced above every app surface, andrender_mode blend_disabledwrites the sample renormalised to the setting’s alpha;Workspace.apply_window_alphahides the copy and the veil at 100 %, so an opaque window pays nothing. Embedded dialogs, file pickers and popup menus draw after the canvas and stay opaque. WhereDisplayServer.is_window_transparency_available()is false - the X11 driver a Wayland desktop runs, unless it is started with--display-driver wayland- the Settings row is still shown, disabled, withSettingsPanel.opacity_hint’s reason beside it: hiding the row read as a feature that was never shipped. - Window transparency needs
transparent_bgand a real display to prove it: with it off, a written 0.5 alpha read back 0.333 (the channel is not 8-bit); the headless display server refusesWindow.transparenteven when it is set directly, so a GUT test asserts the viewport/veil half and the window flag is proven on a headed run.project.godotmust also setdisplay/window/per_pixel_transparency/allowed, or the engine answersis_window_transparency_available()false even on a renderer that supports it. - The boot splash is drawn before the palette exists: the engine paints
application/boot_splash/imagebefore any script or autoload, so the frame cannot readuser://settings.json,UiPalette.active()or the UI scale. It is one fixed picture:project.godotpinsbg_colorand the art’s edges to the darkUiPalette.DARK["SURFACE"](#202128) andtest_boot_splash.gdfails when the image, corners, colour orstretch_modedrift. A theme-following launch is a first-frame overlay, not a second splash; prove the engine’s frame withscripts/screenshot-gpty, becausescripts/ui-captureonly sees the app viewport after the splash. - A CanvasItem material applies to every draw command of that item, not to the item as a whole: the terminal’s grid is one canvas of per-row bands, glyph runs and rects, so a
ShaderMaterialthere runs once per command with the font atlas asTEXTUREand each rect’s tint inCOLOR- a CRT material on the grid treats glyphs as textures and loses every rect’s colour (measured on the orphancrt.gdshader, whoseCOLOR = texture(TEXTURE, uv)made a tinted overlay opaque white). A pane-scale effect gets its own single-command layer instead:PaneEffectsowns the material and the buffer,Layer.EFFECTis onedraw_rector onedraw_texture_rect, and the pane skips its own ground and the row runs at the default background while that layer is active. ATIME-driven effect also belongs in a half-resolutionSubViewportat 30 Hz - full-resolution per-frame shader work is the expensive half (0.29 ms/frame at 1080p and 1.02 ms at 4K for a 4-octave FBM tree, testing.md) - andphaseas a uniform rather thanTIMEkeeps captures repeatable. An additive term is what makes a comb visible on a black ground; multiplying alone changes nothing there. - Palette reads in initializers freeze mode: An
@export var c: Color = UiPalette.active().Xevaluates once at definition time and freezes whichever theme mode was active at construction. Read colors at draw time or useThemetype variations.scripts/check-theme-tokensfails class-bodyUiPalette.active()reads andadd_theme_color_override. - Ancestor theme resolves only after entering the tree: A script probe setting
host.theme = UiTheme.build()and checkingget_theme_stylebox("panel")in the same frame gets Godot’s default theme. Await oneprocess_framefirst for variation lookup to resolve. - Phosphor glyph
Labelinstantiation cost: In Godot 4.7.2,add_childof aLabelcarrying a Phosphor PUA codepoint costs 3.3–3.5 ms (vs. 0.09 ms for ASCII), and re-assigningtexton an attached label costs ~0.00 ms. Update labels and glyphs in place; avoid recreation during workspace or tab switching.
Rendering & Display
- The adapter-type enum is not exposed, and its value is not a software test:
RenderingServer.get_video_adapter_type()exists, butRenderingServer.VIDEO_ADAPTER_TYPE_*is not in GDScript 4.7 (naming one is a parse error), and the value is not a hardware/software flag: on the same desktop the RTX 5070 Ti returned2and llvmpipe0(2026-11-21). Detect a CPU rasterizer by adapter name (RendererInfo.is_software: llvmpipe, softpipe, SwiftShader, Microsoft Basic Render Driver, Apple Software Renderer); the startup[renderer]line and the status bar’s· softwaremarker are the user-visible record. - The primary screen is not the window’s screen:
DisplayServer.screen_get_refresh_rate()with no argument answers the primary display, so a window on a 60 Hz secondary display is capped at the primary’s 165 Hz in one direction and at the wrong rate in the other. UseDisplayServer.window_get_current_screen()and pass it toscreen_get_refresh_rate(screen);screen_get_scale(screen)is the Retina/HiDPI factor the logical viewport is drawn against.RendererInfo.reportandWorkspace._apply_fps_settingare the call sites; a screen change after launch still needs the queued re-apply row. - Glow is gated by the app, not by the engine: Godot 4.7’s renderer matrix lists glow on Forward+, Mobile and Compatibility, but the Compatibility pass was inert for the vault graph in the 2026-11-22 bake-off (turning the guard off changed no channel value by more than 1), so
RendererInfo.supports_glow(method)still returns true only forforward_plus; use the helper, and re-measure before widening it. Do not testget_current_rendering_method() != "gl_compatibility"— it says nothing about Mobile, which the helper covers.
Node Hierarchy, Sizing & Viewports
extends Nodecannot renderControlchildren: OnlyControlnodes render childControls (Label,Button, etc.). ALabelparented to a plainNodeis completely invisible. Containers must extendControl.- Textless Buttons collapse without explicit minimum width/height: Godot does not derive a
Button’s minimum size from child Controls. A button that carries an icon+textHBoxinstead of nativetextneeds an explicitcustom_minimum_size.y. - Width floor inside scroll children freezes layout: Setting
custom_minimum_size.xon aRichTextLabelinside a horizontal-scroll-disabledScrollContainerpropagates upward and prevents shrinking. The container must own width; sync only height fromget_content_height()and re-run onresized. TabContainerowns its internalTabBar’s theme items: The engine copies theTabContainer’s tab styleboxes, font colours and font size onto the internalTabBaras overrides; entries registered onTabBaralone leave the live bar on the engine default (10 px a side plus 1 px borders, 20 px per tab). Set the tab box and font colours on both types -UiThemeshares the sameStyleBoxobjects - and remember the defaultside_marginindents the bar 8 px on the left (zero it when the card already pads). A tab hidden by an overflow reports a zero-based rect fromget_tab_rect(); calculate total width by summing rect widths sequentially.Treedoes not expand on double-click by default:TreeItemdefaults tocollapsed = false, and double-clicking emitsitem_activatedwithout auto-toggling. Code that populates rows on first activation and immediately togglescollapsedcollapses the newly populated folder.- 3D
SubViewportin a pane: Sizing is(0, 0)on the frame the first graph is shown; units-per-pixel calculations must use the Control’s height as a fallback. AnImmediateMeshsurface is committed only onsurface_end(). ClearSubViewportContainervisibility pauses (_hidden_paused) on the visible branch. - Reparenting fires
_exit_tree:Node.reparent()removes and re-adds the node. Subsystems that stop backends on tree exit (cli_view,media,inspector) must checkPaneBody.backend_preservedacross workspace moves.
Focus, Keyboard & Input Handling
- Focus traversal visits disabled buttons:
find_next_valid_focus()filtersFOCUS_NONEand invisibility, but notdisabled. A toolbar whose buttons disable must setfocus_mode = Control.FOCUS_NONEon disabled items, or Tab navigation will land on them. - Input bubbling in Godot 4.7.2:
_gui_inputdoes not bubble to ancestors. An input-stage handler (_input) withgui_get_focus_owner()checks is required to handle global shortcuts like Escape without relying on container bubbling. - Terminal consumes keyboard: A focused
TerminalPaneconsumes all keystrokes in_handle_keyboard. Overlays must capture keyboard ownership on open, and handle Escape before GUI input. - A node visible by default never gets its arrival: layout code can hand the keyboard to an empty surface only on a visibility transition (
was_visiblefalse → true).EmptyStatestarted visible, so the zero-pane first run reportedfocus-owner=<none>; build such a surface hidden and let the layout pass reveal it, then focus its one action (ShortcutGuide.focus_hero). Starting hidden is also what keeps a restored workspace with panes from flashing the guide. - Z-Index does not affect Control picking: Godot GUI mouse picking checks reverse tree order (last sibling first), ignoring
z_index. Overlays must callmove_child(overlay, -1)on open to ensure they receive clicks ahead of earlier siblings. - Tooltip mouse filters: Viewport tooltip lookup skips controls whose
mouse_filterisIGNORE(the default forLabelandRichTextLabel). Controls showing tooltips must setmouse_filter = Control.MOUSE_FILTER_STOPorPASS.
GDScript Syntax, Lifecycles & Typing
- No NUL character in strings: A
\u0000literal decodes as\uFFFDand triggers unexpected NUL character errors at load time. Never use NUL characters for string splitting or composite map keys; use nested dictionaries or structured objects. :=inference fails on untyped Variant:var x := ws._palette._fieldproduces a parse error because reading a property on aVariantbase yieldsVariant. Explicitly type the variable:var x: LineEdit = ws._palette._field.- Typed arrays (
Array[T]): A typed parameterfunc f(arr: Array[Control])rejects a plainArrayat call sites. Furthermore,Array[Dictionary]rejects across the Rust GDExtension boundary; always pass untypedArrayto Rust. - String format operator
%with arrays:"...: %s" % changedwherechangedis anArraytreats the array as the format argument list. If the string has only one%s, it raises a format error for arrays with >1 element. Wrap with% str(changed)or pass explicit tuples. - Default arguments evaluate at script load:
func f(x := some_var)capturessome_varat definition time, not call time. Use sentinel defaults (func f(x := -1)) and resolve dynamic values in the function body. - Reference cycles in
RefCounted: If object A stores object B and object B stores object A, neither is freed on exit. UseWeakRefon the owned child and bind methods directly instead of capturing parent instances in closures. - Autoload callable references: Publishing an inline closure
ShortcutManager.overlay_owns_keyboard = func(): ...captures the enclosing node. When the node is freed, the callable points to dead memory. Reset callbacks in_exit_tree(). - A control must not free the row it lives in from its own signal: a picker’s
item_selectedhandler that rebuilds its container and callsfree()on the old row crashes the engine withObject ... was freed or unreferenced while a signal is being emitted from it(measured 2026-11-21 on 4.7.2, the reactive-effects cue picker). Defer the rebuild (_sync_reactive_rows.call_deferred()); if the rebuild must land in the same frame, free withqueue_free()and tolerate one frame of stale rows.