Skip to content

Instantly share code, notes, and snippets.

@chemscobra
Forked from gruebite/example.gd
Created July 27, 2025 20:08
Show Gist options
  • Save chemscobra/021eae3031259a17a572e6ac11e2a2e3 to your computer and use it in GitHub Desktop.
Save chemscobra/021eae3031259a17a572e6ac11e2a2e3 to your computer and use it in GitHub Desktop.
Godot scene instantiation from class_name
extends Node
func _ready() -> void:
# MyScene is 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: Variant) -> 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: Variant) -> String:
var clss_path := (clss_name as Resource).resource_path
assert(clss_path.ends_with(".gd"), "missing script for class")
var scn_path := clss_path.substr(0, clss_path.rfind(".gd")) + ".tscn"
assert(ResourceLoader.exists(scn_path), "missing scene for class")
return scn_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment