Type Casting

2025/12/27

Type
Learning Resource
Format
Glossary Article
Version
General
Subject Tags
Code
Assets
All else
Copyright 2016-2026, GDQuest
Created
2026/02/16
Updated
2025/12/27

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 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 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))
Become an Indie Gamedev with GDQuest!

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.

Nathan

Founder and teacher at GDQuest
  • Starter Kit
  • Learn Gamedev from Zero
Check out GDSchool

You're welcome in our little community

Get help from peers and pros on GDQuest's Discord server!

20,000 membersJoin Server

Contribute to GDQuest's Free Library

There are multiple ways you can join our effort to create free and open source gamedev resources that are accessible to everyone!