I check properties inside an obj before using them still it generates an error

Godot Version

v4.2.1

Question

I use tweens for smoother health depletion. Even though I check both players before tweeting over their properties still it does not work. Whenever their ref is deleted and the game is still running it generates this error.

Error

Invalid get index ‘health’ (on base: ‘previously freed’).

Code

func update_health():
	var tween = get_tree().create_tween()
	if player_1:
		if "health" in player_1:
			tween.tween_property(hp_bar_P1, "value", player_1.health, .1).set_trans(Tween.TRANS_QUAD)
	if player_2:
		if "health" in player_2:
			tween.tween_property(hp_bar_P2, "value", player_2.health, .1).set_trans(Tween.TRANS_QUAD)

Explanation

Whenever the players are _ready, they assign their ref to the global GameManager script. Which handles basically everything.

Found a Fix

Checking if they are not equal to null stops this problem for now at least but every now and then it generates the same error. Any Tips?

if player_1 != null:
		if "health" in player_1:
			tween.tween_property(hp_bar_P1, "value", player_1.health, .1).set_trans(Tween.TRANS_QUAD)
	if player_2 != null:
		if "health" in player_2:
			tween.tween_property(hp_bar_P2, "value", player_2.health, .1).set_trans(Tween.TRANS_QUAD)

Use @GlobalScope.is_instance_valid() instead.

1 Like

Well @GlobalScope seems to not exist in Godot4. We can write as this

if is_instance_valid(player_1):

Thanks for your help :smiley:

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