Menu
CoddyTech

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 = 100

This 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 constant

A 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 icon

Challenge

Beginner

Declare two constants under the comment:

  • MAX_LIVES with the value 3
  • GRAVITY with the value 9.8

Do not change the print() lines. The program prints:

MAX_LIVES = 3
GRAVITY = 9.8

Try it yourself

extends Node

func _ready():
	# Declare the constants below
	
	# Don't change the lines below
	print("MAX_LIVES = ", MAX_LIVES)
	print("GRAVITY = ", GRAVITY)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler