I’m trying to put a health variable across multiple scenes; at first I thought it wasn’t possible, and I just copied the health variable from one scene to another because the only thing changing the variable was the spacebar (which was a placeholder). So for an example on the main scene, that was the code:
var health = 100
func _ready() -> void:
$Health.text = "Health: " + str(health)
$Health.modulate = Color.WHITE
func _input(event):
if event.is_action_pressed("Space") and health >= 10:
$Health.modulate = Color.RED
await get_tree().create_timer(0.15).timeout
health -= 10
$Health.modulate = Color.WHITE
$Health.text = "Health: " + str(health)
The player code would be like this:
var health = 100
#other code
func _input(event):
if event.is_action_pressed("Space") and health >= 10:
health -= 10
#other code
if health <= 0:
death()
func death ():
$CollisionShape2DA.disabled = true
animated_sprite.play("Death")
But that couldn’t work when I made the enemy scene, and I barely understood signals from Brackeys.
So I watched this tutorial and inferred Autoloads are the same as globals, but when I implemented the tutorial on to my code, it gave me this error message
For such variables, the best way is to use a global script, create a new script, put the variable in it, and add it with a custom name (e.g. Global) in the project settings in the Autoloads tab, now just use Global.health to point it. Example:
I already have the global script but I tried your way and the 3 issues disappeared
but another issue popped up:
I’m not sure what it means, but it pointed at the line that includes “elif.”
if is_on_floor():
if direction == 0:
animated_sprite.play("Idle")
else:
animated_sprite.play("Run")
elif health >= 10 and not is_on_floor():
animated_sprite.play("Jump")
This error shows that health is not an int, I don’t understand why, but:
If you’re using a global health maintenance you can use Global.health here as well, or if that’s true, use int(health)
This is because you accidentally added a break point on this line, this will show up in the form of a red circle on the left side of the line, which will be disabled if you click on it.