How to Access a variable from another scene

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

HI! I need your help please, I always had a troule to pass information between two scenes(prefabs), like, I have this Shelf scene that always will have something different from another like, shelf1 has rice, shelf2 has beans etc.

But in my customer scene I cant access those variables

Customer script:

onready var shelf = preload("res://Shelf.tscn")
func _ready():
# how do I access the variables?

Shelf script:

var contains = "rice"
:bust_in_silhouette: Reply From: samjmiller

A global / autoload singleton is super helpful for storing variables needed across scenes.

For example, create a script called, select “Autoload” from the Project Settings menu, and then any variables or functions stored in that script can be accessed in other scenes & nodes by just prefacing the reference with the script name, like so:

var player_speed = Global.player_speed

A more detailed guide is here:

yeah but they would have the same content right? 'cause if I make the Shelf a singleton, all of the shelfs would have the same variable, I need to access the variable from each shelf, ofr context, my custumer script should get all shelfs and what wich one contains and go to the desired shelf. Like, if the customer wants apples he needs to find the shelf that has apples in it, and I don’t think singletons could handle it

Visni | 2021-07-29 14:53

You could create boolean variables in the global singleton for each shelf + product combo, like:

shelf1_has_apples = true 
shelf2_has_rice = false 

And add a counter to each shelf’s script so that if the inventory of a given product reaches zero, the global boolean is updated to false, like in shelf1:

if apples < 1: 
    Global.shelf1_has_apples = false 

or in shelf2:

if rice > 0: 
    Global.shelf2_has_rice = true

And then when the player needs to query what shelf has apples, you can do something like this:

func what_shelf_has_apples(): 
    if Global.shelf1_has_apples == true 
        print("Shelf 1 has apples!")
    if Global.shelf2_has_apples == true 
         print("Shelf 2 has apples!")     


Unless I am misunderstanding what you wanna do here!

samjmiller | 2021-07-29 15:16

Nice! yeah, that is not the idea, the shelf should not have teh same product forever but i got something with this.
I can make a singlenton storing all shelfs and how many of each products it has

shelf1 = "
shelf1_products = 0
shelf2 = "rice"
shelf2_products = 2

In the customers I just need to check where it is the rice and if it is available

if Shelfs.shelf1 = "rice" and Shelfs.shelf1_products > 0:
#this is the desired shelf

thanks for the help man!

Visni | 2021-07-29 15:47