0 votes

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.

in Engine by (27 points)

1 Answer

0 votes
Best answer

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.

by (341 points)
selected by

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

script 1:

var player_direction = 0

func _ready():

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

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.

Your error:
You copy playernode.playerdirection 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 "playernode.playerdirection" in the fixedprocess 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)

Im not in a computer but i think that the playerdirection 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 playernode.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.

I finally got it to work, thanks :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.