GDScript: How does uninitialized variable works?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By xrbtrx


How does uninitialized variable works in GDScript?
For example, I have an uninitialized variable x with a type of Vector2 (var x: Vector2). If I print it, it shows “(0, 0)”.
Now, if I do “var x: Vector2”, would it be the same as initializing it? such as “var x: Vector2 = Vector2(0, 0)”? or would that mean I initialized it twice (a waste)?

I believe you get the default for the type (although the docs are unclear, beyond var x # null). What the default is is what the engine developers have decided. I don’t think it’s a waste to specify the value you want, just to be sure. For example (a little contrived by stick with me), if the developers decided that a Vector2 was something other than Vector2.ZERO (perhaps an ‘unknown’ value?), you’d have a bug if you never initialised all the variables in your project.

It’s not a waste to assign the value you want, certainly nothing that’s going to affect performance.

spaceyjase | 2023-05-05 11:59