variable value doesn't change when imported in another script

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

i’m accessing a variable from another script but its value doesn’t get updated when it changes in the _fixed_process() function in the 1st script.

:bust_in_silhouette: Reply From: 807

Write the code here.

¿Are you accesing every frame to this variable?, if you want variable value every frame should do that,i think accesing basic types is by “value” not reference.

sorry i didn’t understand what you just said.here is the code though:

script 1:

var player_direction = 0

func _ready():
    set_fixed_process(true)
    
func _fixed_process(delta):
    if Input.is_action_pressed("MoveRight"):
        player_direction = 1
        print("player_direction_script1 =", player_direction)

    elif Input.is_action_pressed("MoveLeft"):
        player_direction = -1
        print("player_direction_script1 =", player_direction)

script 2:

var player_node
var player_direction

func _ready():
    player_node = get_node("/root/level/player")
    player_direction = player_node.player_direction
    set_fixed_process(true)

func _fixed_process(delta):  
    if Input.is_action_pressed("DEBUG_INFO"):
        print("player_direction_script2 =", player_direction)

what’s happening is that it’s printing “player_direction_script2 = 0” nomatter what value its set to in the first script.

PrOoOg | 2017-07-10 06:34

Your error:
You copy player_node.player_direction a single time at startup to the local value player_direction.

This can work with objects like “player_node” because you’d actually copy a reference (kind of a pointer) but won’t work (be updated) with simple types like numbers. They’re just copied by value.

Output “player_node.player_direction” in the _fixed_process in script2. Not the local variable “player_direction”.

func _fixed_process(delta):  
    if Input.is_action_pressed("DEBUG_INFO"):
        print("player_direction_script2 =", player_node.player_direction)

wombatstampede | 2017-07-10 07:05

Im not in a computer but i think that the player_direction var declaration of script 2 should be in the fixed process of script 2 because ready function only executes 1 time at start. Other thing you can do is “omitt” this declaration and access directly to the player_node.player_direction. Object var’s stores entire object reference. But your player direction var only stores a copied value.

Edit: i did’t see previous response. It’s the same with other words.

807 | 2017-07-10 07:16

I finally got it to work, thanks :slight_smile:

PrOoOg | 2017-07-10 16:07