あなた:
GDScript2で、スクリプトからべつのシーンを子ノードとして読み込む方法
GDScript 2.0(Godot 4.x)で、別のシーンをスクリプトから子ノードとして読み込む方法は、以下のようになります。
gdscript# 別のシーンのパス var scene_path := "res://path/to/Scene.tscn" func _ready(): # シーンを読み込み var scene_resource = load(scene_path) as PackedScene if scene_resource: # インスタンス化して子ノードとして追加 var new_scene = scene_resource.instantiate() add_child(new_scene)
PackedScene.instantiate()
が Godot 4 で使われます(Godot 3では instance()
)。
GDScript 2.0 では型指定が強化されています。上記のように明示的に as PackedScene
と書くと安全です。
gdscriptvar parent_node = $SomeNode # または get_node("SomeNode") parent_node.add_child(new_scene)
gdscriptvar new_scene = scene_resource.instantiate() new_scene.some_property = "value" add_child(new_scene)
gdscript@export var enemy_scene_path: String = "res://Enemy.tscn" func spawn_enemy(position: Vector2): var enemy_scene = load(enemy_scene_path) as PackedScene if enemy_scene: var enemy = enemy_scene.instantiate() enemy.position = position add_child(enemy)
必要なら ResourceLoader.load()
を使った非同期読み込みバージョンも紹介できます。やりたいことがもっと具体的なら教えてね!