Skip to content

Instantly share code, notes, and snippets.

@gruebite
Last active August 29, 2025 18:43
Show Gist options
  • Save gruebite/114a7d5c9d5878e5a996294d83649857 to your computer and use it in GitHub Desktop.
Save gruebite/114a7d5c9d5878e5a996294d83649857 to your computer and use it in GitHub Desktop.
Godot scene instantiation from class_name
extends Node
func _ready() -> void:
# MyScene is a `class_name` in a `.gd` script with an associated `.tscn` file
var scene = Instantiate.scene(MyScene)
add_child(scene)
class_name Instantiate
extends Object
## Instantiates a scene based on [param clss_name]. Scene must be located next
## to the associated class.
static func scene(clss_name: GDScript) -> Node:
var scn_path := scene_path(clss_name)
var scn: PackedScene = ResourceLoader.load(scn_path)
var node := scn.instantiate()
return node
static func scene_path(clss_name: GDScript) -> String:
var clss_path := clss_name.resource_path
assert(clss_path.ends_with(".gd"), "missing script for class")
var scn_path := clss_path.get_basename() + ".tscn"
assert(ResourceLoader.exists(scn_path), "missing scene for class")
return scn_path
@Phlegmlee
Copy link

This is brilliant! Have you had any issues with loading more than one scene at a time? Do you use any signals to prevent Resource Loader throwing the error that it is already in use?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment