Why is Godot not applying changes of global (singleton) variables instantly?

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

Hey. I am trying to implement a jump potion into my game which changes the jump height of player from -600 to -1000. I have declared the jump height variable in a script called “globals.gd” which is an enabled singleton.
For some reason the new jump height (of -1000) ist only applied when my KinematicBody2D (the Player) has died and the current scene is reloaded but not when he collects the jump potion (Area2D with signal “body_entered”).

please show the scripts.

whiteshampoo | 2020-05-27 13:27

Sry, my bad. I cut it to the relevant parts.

The Player.gd

var JUMP_HEIGHT = Globals.JUMP_HEIGHT   # globals singleton
func _physics_process(delta):
#The jump part
    if is_on_floor():
	    if Input.is_action_just_pressed("ui_up"):
            motion.y = JUMP_HEIGHT
	    if friction == true:
		motion.x = lerp(motion.x, 0, 0.1)

The jump_potion.gd

func _on_Jump_Potion_body_entered(body):
	if body.name == "Player":
		Globals.JUMP_HEIGHT = -1000
		print("AREA ENTERED")

func _on_Timer_timeout():
	Globals.JUMP_HEIGHT = -600

The globals.gd (singleton)

var JUMP_HEIGHT = -600

Frenggie | 2020-05-27 13:40

:bust_in_silhouette: Reply From: whiteshampoo

Code is VERY relevant :wink:

You create a variable JUMP_HEIGHT and set it in the frist line to the value of Globals.JUMP_HEIGHT. But after that, you never update JUMP_HEIGHT.
JUMP_HEIGHT is just a variable, not a reference. So it does not change, when you change Globals.JUMP_HEIGHT.


  • always use Globals.JUMP_HEIGHT instead of JUMP_HEIGHT
  • update JUMP_HEIGHT on every _physics_process before calculations

PS.: You should not use UPPERCASE-Variable names. Thats for constants and enums :wink:
Of course it works, but can cause confusion if you show your code to others.
(See here)

Thanks. By directly using the global variable, everything works fine. I thought that by changing the reference variable the referenced variable itself will change too.
I guess that’s some pretty stupid beginner mistake xD.

Frenggie | 2020-05-27 19:07