-
-
Save chemscobra/021eae3031259a17a572e6ac11e2a2e3 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 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: 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