Type Casting
2025/12/27
- Type
- Learning Resource
- Format
- Glossary Article
- Version
- General
- Subject Tags
- Created
- Updated
- 2026/02/16
- 2025/12/27
Type casting is when you convert a value from one type to another.
For example, if we had a text field where a user enters some numbers, and we wanted to save them as integers:
var user_input := "10"
var number := int(user_input)More often, we need to convert a number to text so we can display it in a label:
var health := 10
var health_text := "Your health is: " + str(health)Type casting is sometimes referred to as "explicit type casting" to differentiate it from "implicit type casting," which is also called type coercion.
For example, it's also possible in GDScript to automatically convert any value to a string by using string formatting. This conversion is implicit:
var health := 10
var health_text := "Your health is: %s" % [health]One reason to use explicit type casting is to provide Godot with information about a type that you know is correct, but that Godot can't infer.
For example, in the example below, we create a reference to a node, and we know it's a Sprite, but Godot doesn't:
var my_sprite := get_node("Sprite")Godot will assume my_sprite is a plain Node, because it can't detect any additional information about it. We can help it:
var my_sprite: Sprite = get_node("Sprite")I say "help it," but really, Godot doesn't care. It's just a way to make your own code more readable and get good autocomplete.
Another way to type cast is to use the as keyword:
var my_sprite := get_node("Sprite") as SpriteThis is subtly different from the previous example. If get_node("Sprite") returns a node that is not a Sprite, the previous example will throw an error, but this one will return null and not give you any error.
For that reason, it's best used to verify that a node is of a certain type before using it. For example:
func _on_area_entered(area):
var body := area.get_parent() as CharacterBody2D
# if body is not a CharacterBody2D, it will be null
if body != null:
body.move_and_slide(Vector2(0, -1))Don't stop here. Step-by-step tutorials are fun but they only take you so far.
Try one of our proven study programs to become an independent Gamedev truly capable of realizing the games you’ve always wanted to make.
Get help from peers and pros on GDQuest's Discord server!
20,000 membersJoin ServerThere are multiple ways you can join our effort to create free and open source gamedev resources that are accessible to everyone!
Sponsor this library by learning gamedev with us onGDSchool
Learn MoreImprove and build on assets or suggest edits onGithub
Contributeshare this page and talk about GDQUest onRedditYoutubeTwitter…