+2 votes

Hi, sorry for stupid question, but what difference between var speed = 2 and const SPEED = 2? I tried to find on doc page, but no luck or maybe I missed.
Thank you!

in Engine by (111 points)
edited by

2 Answers

+4 votes

const defines a constant variable, once initialized the value can't be changed https://en.wikipedia.org/wiki/Constant_(computer_programming)
var defines a "normal" variable, the value can be changed at any time.

by (486 points)

"constant variable"? A variable varies, otherwise it's not variable.
Just pulling your leg. But the proper terme would be constant value, opposed to variable value.

I thought about that, too but then i decided to stick with the terminology the official documentation uses

But using GDScript I can change the constant value any time and I don't know why.
Constants are not very constant

Why would I want an unchangeable variable?

Constants are helpful in a few ways.

Like a normal variable, you can use them to make your code more readable to others. You can also use them so that the value is defined once in the code and then used in multiple places, if you have to change the value later, then you only need to change one line of code.

Previously constants were used for speed as they did not require extra memory lookups at runtime to retrieve the value. It seems after a quick google search, this no longer seems to hold true for most languages. Not sure if they are faster or not in GDScript.

–1 vote

If it's anything like python then a constant
variable is shared among all instances.
Without constant each instance
gets it's own copy to change.

by (20 points)

To do that you need to autoload (in Project Setting>AutoLoad) a script with 'Global Variable' enabled, then you can access it with the name you set in the autoload tab.
For example: with an AutoLoad script named "Global" you would access it with that name as if it's a variable accessing a node.
So in the AutoLoad script, you do var previous_health then when switching scenes you do Global.previous_health = health and in the other scene you start with health = Global.previous_health
Also, the above comment already answered the question over 3 years after you did.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.