Godot Version
Godot 4.2.2
Question
I’m trying to make a health bar for my game and everything was going smoothly but when I try to change health it says:
Invalid set index ‘value’ (on base: ‘HBoxContainer’) with value of type ‘int’.
This is my code:
extends CharacterBody2D
@onready var life_bar = $“…/GUI/HBoxContainer/Bars/LifeBar”
var hp = 10
const SPEED = 500.0
const JUMP_VELOCITY = -500.0
const SLAM_VELOCITY = 500.0
const DASH_SPEED = 900.0
var dashing = false
var canDash = true
var slamming = false
var canSlam = false
Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)
func _ready():
life_bar.value = hp
func _health_add():
hp += 1
life_bar.value = hp
func _health_subtract():
hp -= 1
life_bar.value = hp
func _physics_process(delta):
# Add the gravity.
if not is_on_floor() or not dashing:
velocity.y += gravity * delta
canSlam = true
else:
canSlam = false
# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
if Input.is_action_just_pressed("ui_dash") and canDash:
dashing = true
canDash = false
$DashTimer.start()
$DashAgain.start()
if Input.is_action_just_pressed("ui_down") and canSlam:
velocity.y = SLAM_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("ui_left", "ui_right")
if direction:
if dashing:
velocity.x = direction * DASH_SPEED
else:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
func _on_dash_timer_timeout():
dashing = false
func _on_dash_again_timeout():
canDash = true
func _on_area_2d_body_entered(body):
_health_subtract()
func _on_heal_body_entered(body):
_health_add()