- Godot Engine Game Development Projects
- Chris Bradfield
- 181字
- 2021-06-18 18:51:31
Updating UI via GDScript
Add a script to the HUD node. This script will update the UI elements when their properties need to change, updating the score text whenever a coin is collected, for example. Refer to the following code:
extends CanvasLayer
signal start_game
func update_score(value):
$MarginContainer/ScoreLabel.text = str(value)
func update_timer(value):
$MarginContainer/TimeLabel.text = str(value)
The Main scene's script will call these functions to update the display whenever there is a change in value. For the MessageLabel, you also need a timer to make it disappear after a brief period. Add a Timer node and change its name to MessageTimer. In the Inspector, set its Wait Time to 2 seconds and check the box to set One Shot to On. This ensures that, when started, the timer will only run once, rather than repeating. Add the following code:
func show_message(text):
$MessageLabel.text = text
$MessageLabel.show()
$MessageTimer.start()
In this function, you display the message and start the timer. To hide the message, connect the timeout() signal of MessageTimer and add this:
func _on_MessageTimer_timeout():
$MessageLabel.hide()