How to get a variable that is changing from another scene.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ArAdev
:warning: Old Version Published before Godot 3 was released.

Hi, I’m having problems importing variables from another scenes that are constantly changing.
The thing Im trying to program is an equip weapon menu. I’m using the Optionbutton node
in a scene, where I store a variable in int numbers (0,1,2,3…) that are the options to choose and when I change the option on the node it change the var number. Is something like this:

extends Node2D

export  var select_weapon=0

func _on_Weapon_option_item_selected( ID ):
if ID==0:
	select_weapon=1
if ID==1:
	select_weapon=2
if ID==2:
	select_weapon=3
if ID==3:
	select_weapon=4

When I import the variable into the player scene, the variable doesn’t change, doesn’t matter how much times I try to change the option , it stays always as the default value(0).
Here is what I try to do in the player’s script:

extends Node2D
var menu = preload("res://Weapon_sel.tscn")
var menuins = menu.instance()

func _ready:
    set_process(true)
func _process(delta):
    var get_weapon= menuins.get("select_weapon")
    print(get_weapon)

It doesn’t matter how much I try to change the option in the menu, the var in the player script always return a 0.

:bust_in_silhouette: Reply From: Zylann

This is not how scenes are supposed to work.
What your player script does currently is to create an instance of Weapon_sel.tscn which is not even added to the tree, and you get the select_weapon using a generic get. So of course, the value you get in the player script is the default one from another instance, NOT the existing one already in game.

What you should do instead is to get the variable from the existing menu. For example, if you have this main scene structure:

Level
    Player
    Menu

Then you can get the selected weapon like this in your player script:

var selected_weapon = get_parent().get_node("Menu").select_weapon

Note that this would work even if you don’t write export (there is also no such thing as “import var” ^^)

Thanks Zylann, I didn’t knew that the way to get the current variable was different, I thought this would work.
It’s good to know this because this is very necessary in the type of game I’m working in. Very useful advice thanks.

ArAdev | 2017-11-23 19:44