Easier @onready bug detection

I thought I’d share something small that I have been doing to make it easier/faster to identify when an @onready reference is wrong. Sometimes I type the reference and make a mistake and other times I refactor and miss a reference - but this picks it up quickly and saves a bunch of debug time for me:

@onready var enemy_hit_sound = $EnemyHitSound

func _ready():
    assert(enemy_hit_sound != null, "FAULT no reference to enemy hit sound")

When the script runs in debug mode it checks the enemy_hit_sound variable to ensure it isn’t null. If it is null then the game stops and the fault message is displayed in the debug window pane. When the game is not built in debug mode the code is removed.

5 Likes

nice share, i havent use assert as yet, but looks like a good way of ensuring its set early on rather than falling over when it comes to getting used.

1 Like

Privacy & Terms