Variable meter issue

Godot Version

4

I am making a horror game and it has a sanity meter, i want it to recharge as you move and if you stand to still it will start to drop, heres my code , its getting stack overflowed?

var sanity = 100

func _ready():
	subtractsanity()

func subtractsanity():
	if Input.is_anything_pressed():
		subtractsanity()
	else:
		await get_tree().create_timer(2.5).timeout
		sanity -= 1
		self.text = str(sanity)+"%"
		subtractsanity()

func _process(delta):
	if Input.is_anything_pressed():
		if sanity < 100:
			sanity += 1```

Assuming your indentation looks like this the function will call itself forever if anything is pressed. Keep in mind scripts/functions run in their entirety and do not wait for events to happen, this will check if anything is pressed and restart the function, since no time has passed something is still pressed, so it restarts the function again and again until your stack overflows.


Make sure to format your pastes

i fixed it , thanks, but i have another question. I have a couple cabins that will detect if the player enters them , how do i have them affect the sanity variable without reparenting a whole mess of things to mess a bunch of things up

Depends on how you want them to affect the player’s sanity. Why would it need reparenting?

i figured it out , i used get_parent() to get another node, i needed the player to be affected by an area3d