Constants
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 12 of 92.
A constant is a value that cannot change after it is created. In GDScript you declare it with the keyword const instead of var:
const MAX_HP = 100This creates a constant named MAX_HP with the value 100. Constant names are written in CONSTANT_CASE: capital letters with underscores between the words.
Assigning a new value to a constant is an error, and Godot reports it before the program runs:
const MAX_HP = 100
MAX_HP = 200 # Error: cannot assign a new value to a constantA constant gets its value in the declaration, so const LIMIT without a value is an error too. A constant can also have a declared type: const GRAVITY: float = 9.8.
Use constants for values that stay the same while the program runs, such as the highest level or the number of lives at the start. The name tells the reader what the number means.
Challenge
BeginnerDeclare two constants under the comment:
MAX_LIVESwith the value3GRAVITYwith the value9.8
Do not change the print() lines. The program prints:
MAX_LIVES = 3
GRAVITY = 9.8Try it yourself
extends Node
func _ready():
# Declare the constants below
# Don't change the lines below
print("MAX_LIVES = ", MAX_LIVES)
print("GRAVITY = ", GRAVITY)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler