How to "change_scene" and pass data?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By JayFi

My app has some buttons, that are filled on startup and set with some data. Then when the button is pressed a scene is loaded.

extends Button

var quiz = null

func lesson_selected():
	Quizzes.set_current_quiz(quiz)
	get_tree().change_scene("res://Quiz.tscn")

I am still a beginner so this is copy and paste code. But I think there is probably something better I can do here yes? Because I don’t know how to pass that “quiz” data object into the scene, I am doing a “set_current_quiz” call to a global object to hold the data. There must be a way to do something like this right?

extends Button

var quiz = null

func lesson_selected():
	s = get_tree().change_scene("res://Quiz.tscn")
    s.set_quiz(quiz)
:bust_in_silhouette: Reply From: cm

This is possible. Try preloading your quiz scene, then setting the quiz data on the instance.

Something like this:

extends Button

var quiz_scene = preload("res://Quiz.tscn")
var quiz = null

func lesson_selected():
    var s = quiz_scene.instance()
    get_tree().change_scene_to(s)
    s.set_quiz(quiz)