Label in Godot – Complete Guide

Labels are an essential component in almost every game UI. They provide informative text to guide players, such as score counters, instructions, or narrative elements in dialogue boxes. Understanding how to manipulate labels effectively in Godot can significantly improve the user experience in your game.

What are Labels in Godot?

Labels are Control nodes in Godot, dedicated to displaying plain text on the screen. They are useful for showing static text, like instructions or game status. Labels are simple but powerful; they can wrap text, align it horizontally and vertically, and are essential for managing UI elements responsive to different screen sizes and resolutions.

What is the Label class used for?

The Label class is designed for text that does not require rich formatting like bold or italics. If you need more complex text features, you’d use a sibling class called RichTextLabel. For straightforward uses, however, Label is more than sufficient. It enables control over text alignment, wrapping, and clipping, providing the flexibility needed for various UI design challenges.

Why should I learn to use Labels?

Being able to use Labels is fundamental for any game developer or UI designer working with Godot. Not only are they involved in displaying crucial gameplay information, but they also allow you to create a readable and accessible interface for your users. Labels are a stepping stone to understanding Godot’s UI system and scripting. They give you the power to make dynamic, interactive elements within your game world.

Whether you’re a beginner in game development or an experienced coder expanding your skill set, learning to manipulate Labels in Godot is an invaluable skill. In the upcoming sections of this tutorial, we’ll dive into coding examples that demonstrate the versatility and functionality of the Label node, making your projects more interactive and engaging.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating a Simple Label

Let’s start by creating a basic label. First, we add a Label node to our scene tree, then we set the text property to display the desired message.

var label = Label.new()
label.text = "Welcome to Zenva Academy!"
add_child(label)

In this case, we’re using GDScript to create a new Label node, set its text, and add it to the current scene’s node hierarchy.

Customizing Label Text

We can customize the font and size of our label’s text by setting the custom_fonts/font property:

var label = $Label
var font = DynamicFont.new()
font.font_data = load("res://path/to/font.ttf")
font.size = 24
label.add_font_override("font", font)

This code loads a custom TrueType Font (.ttf) file, sets its size, and applies it to the label.

Aligning and Wrapping Text

Text alignment and wrapping are important for fitting text within the bounds of the Label node:

var label = $Label
# Align the text to the center
label.align = Label.ALIGN_CENTER
# Enable text wrapping
label.autowrap = true

This example shows how to center align the label’s text and enable wrapping, so the text fits within the node’s bounding rectangle.

Adjusting Label Visibility

Controlling the label’s visibility is straightforward:

var label = $Label
# Hide the label
label.visible = false
# Show the label after a delay (in seconds)
label.visible = true

This piece of the code marks the label as not visible, and then visible again, potentially after a timed gameplay event or delay.

Label Interactivity

To make a label interactive, such as responding to a mouse hover, we need to connect signals and change its properties:

func _ready():
  var label = $Label
  label.connect("mouse_entered", self, "_on_Label_mouse_entered")
  label.connect("mouse_exited", self, "_on_Label_mouse_exited")

func _on_Label_mouse_entered():
  var label = $Label
  label.add_color_override("font_color", Color(1, 1, 0))

func _on_Label_mouse_exited():
  var label = $Label
  label.add_color_override("font_color", Color(1, 1, 1))

In the example above, we set the label to change color when the mouse hovers over it, creating a simple interactive UI component.

With these examples, you’ve seen how to create and customize labels within Godot, giving you insights into the power and flexibility labels offer for UI design in your games.

Manipulating label text dynamically is another important aspect of game development. You can update text in real-time to reflect changes such as scores, timers, inventory counts, and more. Below are several code examples illustrating different ways to interact with and manipulate labels programmatically in Godot.

Updating Score Label in Real Time

func _update_score(new_score):
  $ScoreLabel.text = str(new_score)

This snippet demonstrates a function designed for updating a label that displays a player’s score. It’s a fundamental requirement for games with scoring mechanics.

Implementing a Countdown Timer

func _on_Timer_timeout():
  var time_left = $TimerLabel.text.to_int() # Assuming the label is initialized with a number
  if time_left > 0:
    $TimerLabel.text = str(time_left - 1)
  else:
    # Time's up - handle end of countdown

Here we use the label to show a countdown timer. Each time the attached Timer node times out, we decrement the label’s value until it reaches zero.

Setting Up an Interactive Dialog Label

func _show_dialogue(dialogue_text):
  var dialogue_label = $DialogueLabel
  dialogue_label.text = dialogue_text
  dialogue_label.show()

# Hide the dialog label when the player moves on
func _hide_dialogue():
  $DialogueLabel.hide()

In this example, we’re managing a dialogue label, commonly used in narrative games or ones with story elements. This demonstrates how to show and hide dialogue text as necessary.

Localizing Text Labels

func _set_language(language_code):
  var label = $Label
  label.text = tr(language_code + "_welcome_message")

Localizing your game can greatly increase its appeal. The tr() function is used to set the label’s text to a localized string based on a given language code.

Animating Labels for a Dynamic UI

func _show_alert(message):
  $AlertLabel.text = message
  $AlertLabel.modulate = Color(1, 1, 1, 0)  # Make label transparent
  # Animate label to fade in
  $AlertLabel.animate_property("modulate", Color(1, 1, 1, 0), Color(1, 1, 1, 1), 1, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)

Visibility and opacity can be animated to add flare to UI elements like alerts or notifications. This example fades in an alert label to catch the player’s attention without being disruptive.

Adjusting Label Properties Through Code

func _change_label_look():
  var label = $Label
  # Change the font size
  label.get_font("font").size = 30
  # Change text color
  label.add_color_override("font_color", Color(0.8, 0.4, 0.2))

Customizing the label’s appearance through code allows for dynamic changes during runtime, such as highlighting important game events or notifications.

Through these code examples, you can see the versatility of Labels in Godot. Each snippet gives you a building block for creating a rich, interactive UI tailored to your game’s unique requirements.

We at Zenva believe in empowering learners to create engaging and responsive game interfaces. By mastering these fundamental components like Labels in Godot, you are on your way to crafting incredible user experiences within your games. Keep experimenting and learning with us to see what else you can build!

Continuing our exploration of Label functionalities, let’s delve into more advanced features and techniques, including reacting to in-game events, updating labels with player input, managing multiline text, and creating a typewriter effect for storytelling purposes. These examples will further demonstrate the power of Labels in Godot to enhance your game’s interactive elements.

Reacting to In-Game Events

func _on_Player_health_changed(new_health):
  $HealthLabel.text = "Health: " + str(new_health)

This snippet reflects how to react to in-game events, such as a player’s health change, and update a label accordingly. This is fundamental for action games or any game where the player’s status is crucial.

Updating Labels with Player Input

func _input(event):
  if event is InputEventKey and event.pressed and event.scancode == KEY_ENTER:
    var name = $NameInput.text  # Assuming NameInput is a LineEdit node for player's name input
    $WelcomeLabel.text = "Welcome, " + name + "!"

Handling player input is crucial for personalizing the gaming experience. In this example, when the player presses “Enter”, their input is captured from a text field and reflected in a welcoming label.

Managing Multiline Text

# Assume we receive a long string that we want to display in a label
func _display_multiline_text(text):
  $MultilineLabel.text = text
  $MultilineLabel.autowrap = true
# The 'autowrap' property makes sure the text does not exceed the label width

Multiline text is often required for displaying longer messages or descriptions in your game. Setting the ‘autowrap’ property to ‘true’ ensures text doesn’t exceed the bounds of the label.

Typewriter Effect

func _start_typewriter_effect(text, interval=0.05):
  $StoryLabel.text = ""
  for i in range(text.length()):
    yield(get_tree().create_timer(interval), "timeout")
    $StoryLabel.text += text[i]

# Call this in your code where you want to start the effect
_start_typewriter_effect("Once upon a time in a game far, far away...")

The typewriter effect is a classic narrative tool in games to add suspense or focus to the story text. This is achieved by gradually displaying the text one character at a time.

Adjusting Label’s Rect Transform through Code

func _move_label_to(new_position):
  $FloatingLabel.rect_position = new_position  # Move label to a new position on the screen

For floating text effects or labels that need to move within your game scene, adjusting the Label’s ‘rect_position’ property dynamically can create a more lively UI.

While working with Labels, remember to take advantage of Godot’s signal system, which can help you create more reactive and dynamic user interfaces. Connect UI signals to your game logic to ensure that updates to the UI, like label text changes, are closely tied to gameplay events.

These additional examples of Label usage in Godot demonstrate how to harness text-based UI elements to improve player engagement and communicate important game information clearly. Leveraging advanced features allows for even more creative and compelling game experiences that resonate with players.

We at Zenva are committed to providing comprehensive resources for learning and mastering game development techniques. By including these interactive and advanced examples within your Godot projects, you’re well on your way to creating polished and immersive games that stand out in the digital landscape. Happy coding!

Continue Your Game Development Journey with Godot

Embarking on your game development journey is just the beginning, and there’s much more to explore and master in Godot. To keep the momentum going and to further expand your skills, we invite you to check out our Godot Game Development Mini-Degree. This collection of courses dives into various aspects of game development, providing you with a comprehensive understanding of the Godot engine, GDScript, and beyond. Suitable for enthusiasts of all levels, this mini-degree is the perfect next step, whether you’re starting out or looking to sharpen your existing skills with the latest techniques.

Our Godot courses cover a broad range of topics and ensure that you have the tools and knowledge to create both 2D and 3D games. As you progress, you’ll find yourself equipped to tackle more complex projects and refine your abilities to produce professional-quality games. You can see our entire collection of Godot courses here.

At Zenva, we’re passionate about helping you make your mark in the world of game development. With over 250 supported courses, our project-based learning approach not only boosts your career but also empowers you to build an impressive professional portfolio. So, continue your learning adventure with us, and create the games you’ve always dreamed of!

Conclusion

Labels in Godot are foundational to crafting an immersive and intuitive game experience. By exploring the various ways to integrate, animate, and manage labels, you’ve equipped yourself with essential skills to enhance your game’s user interface. Remember, the subtleties of how you present information to your players can significantly impact the enjoyment and success of your game. Take these lessons to heart, and you’ll be well on your way to creating polished and captivating games with Godot.

Don’t stop here – your game development journey is filled with endless possibilities and learning opportunities. Dive deeper, refine your skills, and expand your knowledge with our Godot Game Development Mini-Degree. Let the power of Godot unlock your creative potential and help you manifest the games you envision. Join us at Zenva, where your game development adventure continues to evolve, and together, we can shape remarkable gaming experiences for players around the world.

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.