How to get the value of a variable from another scene ?

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

Hello,

im making a simple game for my coursework, i have a coin scene, menu scene, and level scene. i want to show how much i collect coin on level to menu scene but i dont know how.
help me please

:bust_in_silhouette: Reply From: AiTechEye
get_tree().get_root().get_node("Spatial/node1/node2").get("variable")

The other way is by adding the scenes in [project settings] > [AutoLoad]

so, if you adds level 1, and name it to level1, then you can get access to it like:

level1.get_node("node1").get("coins_variable")
:bust_in_silhouette: Reply From: Eric Ellingson

You can use an autoloaded script to save/share state between scenes. See Singletons (AutoLoad) — Godot Engine (3.1) documentation in English for getting it set up.

Here is a minimal use case outline:

# GameState.tscn
var coins_collected = 0

Then in your level scene (I don’t know how you are detecting when a coin is collected, but just move this to wherever that might be)

# Level.tscn

func _on_coin_collected():
    GameState.coins_collected += 1

Then in your menu scene:

# Menu.tscn

func _ready():
    $CoinsLabel.text = str(GameState.coins_collected)

hi why do you put dollar sign in front of the code?
Necessary?

Okan Ozdemir | 2019-09-23 19:47

Assuming the node that the script is attached to has a child node called CoinsLabel, instead of using get_node("CoinsLabel"), you can use the $ short-hand and just reference it as $CoinsLabel

Eric Ellingson | 2019-09-23 20:59

:bust_in_silhouette: Reply From: sepp

I have founded a good Video to your question

:bust_in_silhouette: Reply From: Andrew Wilkes

You need to understand and make use of signals. We need to make our scenes independent of outside scenes. Your scene should work stand-alone for testing purposes. Have a look at my tutorial here to get a solid understanding of this topic: Signals in Godot