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.
var
keyword to signify the creation of a variablevar
keyword, come up with a name for the newly created variable=
symbol to assign a value to your variable. The =
character is also called the assignment operator=
character, assign a literal value to your 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.
var a
var b
var c
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
a
can only be assigned integer values.b
can only be assigned string values.c
can only be assigned float values.d
can only be assigned boolean values.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
a
can only be assigned integer values.b
can only be assigned string values.c
can only be assigned float values.d
can only be assigned boolean values.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
text
has the value of 100 transformed into a string value.num
has the value “100” transformed into an integer value.numFloat
has the value of 100 converted into a float value.Variables | Godot GDScript | Ep 1.1 video & article by Godot Tutorials is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .