🧪 What Type Is That? Understanding int, float, and Type Checking in GDScript
Now that I’ve learned how to use integers and floats in GDScript, it’s time to take a closer look at how Godot actually handles types behind the scenes.
At first glance, it might seem like all numbers behave the same. You declare a variable, assign a number, print it—and boom, done. But how do we really know whether a value is treated as an int or a float?
🔍 Using typeof() in GDScript
Godot provides a built-in function called typeof() that returns a special constant representing the type of a given value. These are internal type IDs, so instead of saying “this is an int” or “this is a float,” you’ll see numbers like 2, 3, or 4.
GDScript Type Codes with typeof()
| Type Constant | Value | Description |
|---|---|---|
TYPE_NIL | 0 | Null / Empty |
TYPE_BOOL | 1 | Boolean (true/false) |
TYPE_INT | 2 | Integer |
TYPE_FLOAT | 3 | Decimal number |
TYPE_STRING | 4 | Text |
Here’s an example script I used to test this:
func _ready() -> void:
var num = 1.5
print("Type of num:", typeof(num)) # Outputs 3
print("------------------------")
print("Hello float:", num)
This confirmed that 1.5 is treated as a float and returns 3 from typeof().
Then I tested an integer:
var num = 1
print("Type of num:", typeof(num)) # Outputs 2
And a string:
var text = "Hello"
print("Type of text:", typeof(text)) # Outputs 4
🧠 Why This Matters
typeof()helps you confirm what type you’re working with—especially useful when dealing with dynamic values or debugging.- The output of
typeof()is machine-readable, not human-friendly (it returns integer IDs), but it’s still super helpful. - Even without declaring the type directly, Godot infers the type from the value you assign.
✅ What I Learned
- GDScript supports built-in types like
int,float, andString. - You don’t need to declare types explicitly—Godot figures it out for you.
typeof()helps reveal the underlying type of any variable.- This is great for debugging or learning how different data types behave.
This little experiment gave me a better understanding of how Godot sees the data I’m working with—and that’s a big step forward in learning to code confidently!