Hello and welcome to the GDScript fundamental tutorial series.
In this episode, I go over variables in Godot GDScript.
In computer science, a variable stores information to be referenced to and manipulated in a computer program.
In GDScript, you define a variable using the var keyword.
You need to have 4 crucial things in a single line of code to write a variable.
In the following example, the values a, b, and c are variables:
var a = "hello world"
var b = 100
var c = 9.5
The answer is, no, you don’t have to.
A variable without a value is called an uninitialized variable.
This means that a variable is declared, but no value has been assigned to it.
The variables a, b, c are variables
Godot allows you to write typed variables.
This limits a variable to only contain values of a specific data type.
To create a typed variable, all you have to do is use the colon symbol (:) followed by the data type.
var a: int = 100
var b: String = "Hello world"
var c: float = 98.9
var d: bool = true
You can also infer the data type by the value being assigned to the variable:
var a := 100
var b := "Hello World"
var c := 98.9
var d := true
In Gdscript, values assigned to a typed variable must have a compatible type.
If you need to coerce a value to be a particular type, you can use the casting operator keyword as.
var text: String = 100 as String
var num: int = "100" as int
var numFloat: float = 100 as float