Menu
CoddyTech

External Files

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 1 of 65.

Real programs are split into several files. Each .gd file is a script, and one script can use another.

Write class_name at the top of a script to give it a global name. Every other script in the project can then use that name directly, with no import line:

# greeter.gd
class_name Greeter
extends RefCounted

static func greet(player_name: String) -> String:
	return "Hello, " + player_name + "!"

static func makes a function you call through the script name, Greeter.greet("Ada"). extends RefCounted is the plain base for scripts that are not nodes; the next lessons explain it.

# main.gd
extends Node

func _ready():
	print(Greeter.greet("Ada")) # Hello, Ada!

The program still starts in _ready() of main.gd. The other files only define things that main.gd uses.

Godot names files in snake_case and the class_name in PascalCase: class_name Greeter lives in greeter.gd. Keep one class per file.

A script without class_name can be loaded by its path with preload():

const Helpers = preload("res://helpers.gd")

func _ready():
	print(Helpers.shout("hi")) # HI!
challenge icon

Challenge

Easy

Write the static function greet in greeter.gd. It takes a player name and returns Hello, NAME!. When the name is empty, it returns Hello, friend!.

The supplied code reads how many names follow, then prints Greeter.greet() for each one. For the names Ada and an empty line it prints:

Hello, Ada!
Hello, friend!

Your code goes in greeter.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var count := int(OS.read_string_from_stdin())
	for i in count:
		print(Greeter.greet(OS.read_string_from_stdin()))
quiz iconTest yourself

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

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler