Godot is a game engine that’s been around for a while and is finally gaining traction in the industry. It’s completely open-source, so you can do anything you want with it for free. With that said, unlike Unity(C#), Godot has its own scripting language known as GDScript. It’s very similar to Python; for more information take a look at my Python post for basics. Today, we’ll go over the important bits that set GDscript apart from Python — starting with variables.
Just like any programming language, Godot has support for variables. The syntax is slightly different from Python. In Python, you simply declare a variable with its name; in Godot, declaring variables can be done with the const or var keyword with subtle differences.
The const keyword is used when the variable is constant; that means it should not be changed after it is declared and initialized. This is extremely useful for values that you want to use everywhere that stay the same(like PI). Now, here’s an example of a constant variable:
As you can see, the only defining factor is that we use the const keyword. As mentioned before, we can no longer change this value. Now, that we know about constants, let’s talk about regular variables.
Var is the keyword that you will use the most. Unlike const, you can reassign the variable. This means that you can adjust the value as you need to. Here’s an example to illustrate:
Again the only difference is the keyword change. It’s not that different from Python. Also, just like Python, GDScript has support for types with variables. Let’s get into types.
Types are not required in GDScript, but they are useful. The advantage of types in GDScript is that the code will not run if the types do not match. In Python, the code will run even if the types don’t match. In GDScript, you can assign types in two ways: one is implicit, the other is explicit; let’s see the differences.
The explicit syntax is exactly like Python syntax in the latest version:
As you can see, we add the type with a colon, before we assign the value; in this case, the type is int and the value is 400. So, we know what the explicit version looks like; what’s the implicit version like?
The implicit version is different. The implicit assumes the type based on what you assign. Here’s an example:
As you can, the main difference is that “:=” is used to assign the value; we’ve deleted int and assume 400 is the right value. In most cases, use the explicit version as it is easier to understand the types in your code that way.
I hope this short introduction helped you. Stay tuned as we talked about functions next!
Good luck with creating your own games!