Saving variables through scenes

Godot Version

4.3

Question

So I made a variable attached to a scene called “stone” that increases by 1 every time I press a button but once I press another button that sends me to different scene it resets back to 0 and switching to the previous scene resets it again.

Is there a way to save variables through scenes? I’ve tried using global scripts but they only seem to work with keyboard keys and I specifically need buttons

You can edit a global’s variables through any other script. In your button, or where ever you want to edit the stone value, replace the variable with your global’s Global.stone += 1

Might be a good idea to look into save files too.

Where exactly do I place the global variable, can you give me an example?

You define the variable inside of the global script

extends Node

var stone: int = 0

Then you can use this variable in any script when prefaced with the global name you assigned it in the project settings, like Global.stone.

Maybe you could show how you tried to use the global script, I’m not sure where it went wrong for you without that information.

extends Node

var stone1: int = 0


func _ready() -> void:
	pass


func _process(delta: float) -> void:
	pass

func _input(event):
	if event.is_action_pressed("MineStone"):
		print(stone1)
		stone1 -= 1
		
	

func _on_stone_pressed():
	print(stone1)

Is there a problem with this script or could it be that I’m doing something wrong with the non-global one?

you are certainly using the non-global stone1 variable, what did you name your global in the project settings?

I named it “Stone1”
Is it supposed to be var Global:stone1: int = 0?
or do I need to put Global: every time I use stone1?

A global is a different script that is loaded along with the current scene and is globally accessable by all scripts

I finally figured out how it works, thank you

Would a static variable not be enough? Why make the whole thing a singleton?

extends Node

static var stone1: int = 0