🧵 Strings in GDScript: Let’s Talk Text!
So far we’ve printed numbers, worked with floats, and learned about types. But what if we want to show names, dialogue, messages, or any kind of text? That’s where strings come in.
A string is just a bit of text—letters, numbers, or symbols—wrapped in quotation marks. For example:
var greeting = "Hello, world!"
Godot knows this is a string because of the "
quotes.
🧪 String Concatenation
Just like any other programming language, GDScript, which is a high-level, dynamically-typed programming language used to create content in the Godot engine, makes use of string concatenation. It is a method that links or merges two or more strings.
Learning how to concatenate strings is pivotal as it helps in setting up dialogues in your game, displaying instructions, or even for debugging purposes.
Basic Syntax for String Concatenation
GDScript uses the +
operator to concatenate or link two strings. This is a straightforward way to concatenate, and you’ve probably used something similar in other languages.
You can print strings just like numbers:
func _ready():
var name = "Link"
print("Welcome, " + name + "!")
Output:
Welcome, Link
🔄 Combining Strings and Numbers
You can’t directly combine a string and a number like this:
print("Score: " + 100) # ❌ This causes an error!
But you can convert the number to a string using str()
:
print("Score: " + str(100)) # ✅ Works!
🔢 String Length and Access
Want to know how long a string is? Or grab a specific letter?
var phrase = "Godot"
print(phrase.length()) # 5
print(phrase[0]) # G
✂️ Slicing Strings
You can grab parts of a string (called slicing):
var word = "developer"
print(word.substr(0, 3)) # dev
substr(start, length)
cuts out a piece of the string starting at a certain point.
🔁 String Methods You’ll Love
Here are some super useful things you can do with strings:
var text = "Hello, GODOT!"
print(text.to_lower()) # hello, godot!
print(text.to_upper()) # HELLO, GODOT!
print(text.find("GODOT")) # 7 (starts at index 7)
💡 Why Strings Matter in Games
Strings show up everywhere in game dev:
- Menus
- Dialogues
- Player names
- Score messages
- UI labels
Understanding how to use and format strings makes your games more interactive and polished.
✅ Recap
- A string is text inside quotes (
"like this"
). - Combine with
+
, convert numbers withstr()
. - Use
.length()
,.substr()
, and more to work with text. - Strings are essential for UI, messages, and player feedback.