See all glossary terms

Static Function

A static function is a function that only runs calculations on its inputs and returns a value. It is bound to a class rather than an object (an instance of that class).
It means that static functions don't have access to the properties of the class, which only exist on instances. This doesn't sound too useful, does it?
Well, the good news is, you can call a static function without creating an instance of the class! So they're great for utility functions that don't need to know anything about the class they're in.
You could use static functions for things like:
  • Math calculations (geometry, physics, etc.)
  • Generating data for procedural levels
  • Listing all the files in a directory
  • Processing and modifying text
And more.
To define a static function in GDScript, you use the static keyword before the function definition. Here's an example of a function that finds all the files with a specific file extension in a directory (".png", ".mp3", etc.) :
static func find_files_in_directory(directory_path: String, file_extension: String) -> Array[String]:
	var file_names := DirAccess.get_files_at(directory_path)
	var file_paths: Array[String] = []
	for file_name in file_names:
		if file_name.get_extension() != file_extension:
			continue
		file_paths.append(directory_path.path_join(file_name))
	return file_paths

See Also

Related terms in the Glossary