How can I Synchronize values between another scene?

Hi! I’m making a health system!
And I need your help!

The part that I need help with is delivering the value of hp to another scene (of course Including the scene that was changed during the game!)

Because I devided the game into battle scene and main scene

So I need to share hp value between battle scene and main scene

I would say How can I synchronize values between another scene?

How can I do this?

Could you help me?

PS. I’m not native English speaker and if my English was bad I’m sorry about this…

There are several ways you could do this, though which is best depends on your needs. I would, personally, add the player health to a resource and set it as a singleton. It would look something like this:

~~GlobalVariables.gd~~
static var player_health: int = 100

~~MainScene.gd~~
var player_hp: int = GlobalVariables.player_health

And then doing the same thing in your BattleScene.gd. As long as you reference the GlobalVariables list with any/all changes you make, it should update correctly. Just note that, once the value is updated, you have to manually change it back again (if adding/removing more health or restarting the scene upon death).

Is there any way to do it perfectly automatically?
(Thank you so much for your help!)

There is, somewhat. When you have singletons/autoloads, they can also call functions. So, if you want to say, subtract 10 health from the player_health in GlobalVariables, you could do:

~~GlobalVariables.gd~~
static var player_health: int = 100

static func change_health(value: int) -> void:
	player_health += value     

Where (value) is passed to it from the other scenes:

~~MainScene.gd~~
var player_hp: int = GlobalVariables.player_health

func make_player_hurt() -> void:
        GlobalVariables.change_health(-10) #-1 here is passed to the GlobalVariables function and replaces 'value' with '-10'
1 Like

What a good idea!! Thank you so much!! and thank you again!!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.