3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Godot] シーン遷移する際の遷移先シーンにデータを渡す

Posted at

Godot 4.2

シーン遷移する際の遷移先シーンにデータを渡したい。
autoloadでグローバルなノードに変数を置く以外の方法がないか。

試行錯誤したがこれ↓で行けた。

シーンの遷移をいつもchange_scene_to_file(),change_scene_to_packed()を使っていたのでそれ以外の遷移の方法がないと思っていたのだが、ガサッと遷移をするというよりは、シーンツリー下のノードを手作業で入れ替えることで結果としてシーンの遷移を実現する、ということなんだろう。

  • 新シーンをload/preload→instantiate()
  • 新シーンのインスタンスにメソッド経由で現在シーンからデータを渡す
  • 現シーンのNodeインスタンスを一時変数に保持
  • 新シーンをシーンツリーのルートの子ノードに追加
  • シーンツリーのcurrent_sceneを新シーンに変更
  • 現シーンを遅延しつつ解放

シーンAのスクリプト

scene_a.gd
extends Node
var scene_b

func _ready():
    scene_b = preload("res://scene_b.tscn")

func _on_button_button_down():
    var node_b = scene_b.instantiate()
    node_b.set_hoge(123)
    var node_a = get_tree().current_scene
    get_tree().root.add_child(node_b)
    get_tree().current_scene = node_b
    node_a.call_deferred("free")

シーンBのスクリプト

scene_b.gd
extends Node
var hoge: int

func set_hoge(i: int):
    hoge = i

func _on_button_button_down():
    print("hoge = " + str(hoge))
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?