See all glossary terms

Type Casting

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 a 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 coerction.
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 Sprite
This 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))

See Also

Related terms in the Glossary