Embed Directive in GDScript

Here’s the translation of the Go code to GDScript, formatted in Markdown suitable for Hugo:

Our first program will demonstrate embedding files and folders into the binary at build time. Here’s the full source code:

extends Node

# GDScript doesn't have a direct equivalent to Go's embed directive.
# Instead, we can use Godot's built-in functionality to load files.

# Load the contents of a single file as a string
var file_string = preload("res://folder/single_file.txt").get_as_text()

# Load the contents of a single file as a byte array
var file_byte = preload("res://folder/single_file.txt").get_buffer()

# Load multiple files from a folder
var folder = load("res://folder")

func _ready():
    # Print out the contents of 'single_file.txt'
    print(file_string)
    print(file_byte.get_string_from_utf8())

    # Retrieve some files from the loaded folder
    var content1 = load("res://folder/file1.hash").get_as_text()
    print(content1)

    var content2 = load("res://folder/file2.hash").get_as_text()
    print(content2)

In GDScript, we don’t have a direct equivalent to the embed directive. However, we can achieve similar functionality using Godot’s resource system and file loading capabilities.

To use this script:

  1. Create a new Godot project.
  2. Create a folder named “folder” in the project’s root directory.
  3. Add the following files to the “folder”:
    • single_file.txt with the content “hello godot”
    • file1.hash with the content “123”
    • file2.hash with the content “456”
  4. Create a new script, paste the above code, and attach it to a Node in your scene.

When you run the scene, you should see the following output:

hello godot
hello godot
123
456

Note that in GDScript, we use the preload and load functions to read file contents. preload is used for files that are known at compile-time and will be included in the exported project, while load can be used for dynamically loading resources at runtime.

The get_as_text() method is used to get the content of text files, while get_buffer() can be used to get the raw byte data of a file.

This approach allows you to include arbitrary files in your Godot project and access them at runtime, similar to the embed directive in Go.