Display fuel in the label

I have a code to the main character and have a label detached to the camera2d which is the child of CharacterBody2d. I want to make the jetpack_fuel variable shown on the label that is also called jetpack_fuel :

extends CharacterBody2D

var speed = 200
const jump_velocity = -400
var direction = Vector2()
var jetpack_fuel = 100
var jetpacking = false
@onready var sprite_2d = $Sprite2D

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var animation = 'idle'

func _jetpacking(delta):
	if Input.is_action_pressed("Jump") and jetpack_fuel > 0:
		velocity.y = jump_velocity * 0.5 
		jetpack_fuel -= 10 * delta 
		animation = 'jetpacking' 
	else:
		velocity.y += gravity * delta 
		if not is_on_floor():
			animation = 'jumping' 

func _walking_n_running():
	direction = Input.get_axis("GoLeft", "GoRight")
	if direction != 0:
		velocity.x = direction * speed
		if speed > 200 and is_on_floor():
			animation = "running"
		if speed <= 200 and is_on_floor():
			animation = "walking"
	else:
		velocity.x = move_toward(velocity.x, 0, 16)
		if is_on_floor():
			animation = "idle"	

func _jump(delta):
	jetpacking = true
	if is_on_floor() and Input.is_action_just_pressed("Jump"):
		velocity.y = jump_velocity
		animation = 'jumping'
		jetpacking = false
	elif not is_on_floor():
		_jetpacking(delta)
func _running():
	if Input.is_action_pressed('Sprint'):
		speed = 280
	else:
		speed = 200

func _flip():
	if Input.is_action_just_pressed('GoLeft'):
		sprite_2d.flip_h = true
	if Input.is_action_just_pressed('GoRight'):
		sprite_2d.flip_h = false

func _physics_process(delta):
	_jump(delta)
	_walking_n_running()
	_running()
	_flip()
	move_and_slide()
	sprite_2d.animation = animation


You can update the label as you update your variable, I recommend a @export variable so you can assign the Label node wherever it may be from the editor.

@export var jetpack_fuel_label: Label

func _jetpacking(delta):
	if Input.is_action_pressed("Jump") and jetpack_fuel > 0:
		velocity.y = jump_velocity * 0.5 
		jetpack_fuel -= 10 * delta

		jetpack_fuel_label.text = "%d" % jetpack_fuel

		animation = 'jetpacking'
1 Like

For one of my game demos I was even lazier - I created a RichTextLabel node and attached a script to that.

extends RichTextLabel

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

func _process(delta):
	text = ("Ammo " + str(global.magazine) + "\n" + "Bombs " + str(global.bombs))