Last active
July 31, 2025 23:22
-
-
Save gruebite/114a7d5c9d5878e5a996294d83649857 to your computer and use it in GitHub Desktop.
Godot scene instantiation from class_name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment