Runtime file loading and saving

See also

See Saving games for information on saving and loading game progression.

Sometimes, exporting packs, patches, and mods is not ideal when you want players to be able to load user-generated content in your project. It requires users to generate a PCK or ZIP file through the Godot editor, which contains resources imported by Godot.

Example use cases for runtime file loading and saving include:

  • Loading texture packs designed for the game.

  • Loading user-provided audio tracks and playing them back in an in-game radio station.

  • Loading custom levels or 3D models that can be designed with any 3D DCC that can export to glTF (including glTF scenes saved by Godot at runtime).

  • Using user-provided fonts for menus and HUD.

  • Saving/loading a file format that can contain multiple files but can still easily be read by other applications (ZIP).

  • Loading files created by another game or program, or even game data files from another game not made with Godot.

Runtime file loading can be combined with HTTP requests to load resources from the Internet directly.

Warning

Do not use this runtime loading approach to load resources that are part of the project, as it’s less efficient and doesn’t allow benefiting from Godot’s resource handling functionality (such as translation remaps). See Import process for details.

See also

You can see how saving and loading works in action using the Run-time File Saving and Loading (Serialization) demo project.

Plain text and binary files

Godot’s FileAccess class provides methods to access files on the filesystem for reading and writing:

  1. func save_file(content):
  2. var file = FileAccess.open("/path/to/file.txt", FileAccess.WRITE)
  3. file.store_string(content)
  4. func load_file():
  5. var file = FileAccess.open("/path/to/file.txt", FileAccess.READ)
  6. var content = file.get_as_text()
  7. return content

To handle custom binary formats (such as loading file formats not supported by Godot), FileAccess provides several methods to read/write integers, floats, strings and more. These FileAccess methods have names that start with get_ and store_.

If you need more control over reading binary files or need to read binary streams that are not part of a file, PackedByteArray provides several helper methods to decode/encode series of bytes to integers, floats, strings and more. These PackedByteArray methods have names that start with decode_ and encode_. See also Binary serialization API.

Images

Image’s Image.load_from_file static method handles everything, from format detection based on file extension to reading the file from disk.

If you need error handling or more control (such as changing the scale an SVG is loaded at), use one of the following methods depending on the file format:

Several image formats can also be saved by Godot at runtime using the following methods:

The methods with the to_buffer suffix save the image to a PackedByteArray instead of the filesystem. This is useful to send the image over the network or into a ZIP archive without having to write it on the filesystem. This can increase performance by reducing I/O utilization.

Note

If displaying the loaded image on a 3D surface, make sure to call Image.generate_mipmaps so that the texture doesn’t look grainy when viewed at a distance. This is also useful in 2D when following instructions on reducing aliasing when downsampling.

Example of loading an image and displaying it in a TextureRect node (which requires conversion to ImageTexture):

  1. # Load an image of any format supported by Godot from the filesystem.
  2. var image = Image.load_from_file(path)
  3. # Optionally, generate mipmaps if displaying the texture on a 3D surface
  4. # so that the texture doesn't look grainy when viewed at a distance.
  5. #image.generate_mipmaps()
  6. $TextureRect.texture = ImageTexture.create_from_image(image)
  7. # Save the loaded Image to a PNG image.
  8. image.save_png("/path/to/file.png")
  9. # Save the converted ImageTexture to a PNG image.
  10. $TextureRect.texture.get_image().save_png("/path/to/file.png")

Audio/video files

Godot supports loading Ogg Vorbis audio at runtime. Note that not all files with an .ogg extension may be Ogg Vorbis files. Some may be Ogg Theora videos, or contain Opus audio within an Ogg container. These files will not load correctly as audio files in Godot.

Example of loading an Ogg Vorbis audio file in an AudioStreamPlayer node:

  1. $AudioStreamPlayer.stream = AudioStreamOggVorbis.load_from_file(path)

Example of loading an Ogg Theora video file in a VideoStreamPlayer node:

  1. var video_stream_theora = VideoStreamTheora.new()
  2. # File extension is ignored, so it is possible to load Ogg Theora videos
  3. # that have an `.ogg` extension this way.
  4. video_stream_theora.file = "/path/to/file.ogv"
  5. $VideoStreamPlayer.stream = video_stream_theora
  6. # VideoStreamPlayer's Autoplay property won't work if the stream is empty
  7. # before this property is set, so call `play()` after setting `stream`.
  8. $VideoStreamPlayer.play()

Note

Godot doesn’t support runtime loading of MP3 or WAV files yet. Until this is implemented, it’s feasible to implement runtime WAV loading using a script since AudioStreamWAV‘s data property is exposed to scripting.

It’s still possible to save WAV files using AudioStreamWAV.save_to_wav, which is useful for procedurally generated audio or microphone recordings.

3D scenes

Godot has first-class support for glTF 2.0, both in the editor and exported projects. Using GLTFDocument and GLTFState together, Godot can load and save glTF files in exported projects, in both text (.gltf) and binary (.glb) formats. The binary format should be preferred as it’s faster to write and smaller, but the text format is easier to debug.

Example of loading a glTF scene and appending its root node to the scene:

  1. # Load an existing glTF scene.
  2. # GLTFState is used by GLTFDocument to store the loaded scene's state.
  3. # GLTFDocument is the class that handles actually loading glTF data into a Godot node tree,
  4. # which means it supports glTF features such as lights and cameras.
  5. var gltf_document_load = GLTFDocument.new()
  6. var gltf_state_load = GLTFState.new()
  7. var error = gltf_document_load.append_from_file("/path/to/file.gltf", gltf_state_load)
  8. if error == OK:
  9. var gltf_scene_root_node = gltf_document_load.generate_scene(gltf_state_load)
  10. add_child(gltf_scene_root_node)
  11. else:
  12. show_error("Couldn't load glTF scene (error code: %s)." % error_string(error))
  13. # Save a new glTF scene.
  14. var gltf_document_save := GLTFDocument.new()
  15. var gltf_state_save := GLTFState.new()
  16. gltf_document_save.append_from_scene(gltf_scene_root_node, gltf_state_save)
  17. # The file extension in the output `path` (`.gltf` or `.glb`) determines
  18. # whether the output uses text or binary format.
  19. # `GLTFDocument.generate_buffer()` is also available for saving to memory.
  20. gltf_document_save.write_to_filesystem(gltf_state_save, path)

Note

When loading a glTF scene, a base path must be set so that external resources like textures can be loaded correctly. When loading from a file, the base path is automatically set to the folder containing the file. When loading from a buffer, this base path must be manually set as there is no way for Godot to infer this path.

To set the base path, set GLTFState.base_path on your GLTFState instance before calling GLTFDocument.append_from_buffer or GLTFDocument.append_from_file.

Fonts

FontFile.load_dynamic_font supports the following font file formats: TTF, OTF, WOFF, WOFF2, PFB, PFM

On the other hand, FontFile.load_bitmap_font supports the BMFont format (.fnt or .font).

Additionally, it is possible to load any font that is installed on the system using Godot’s support for System fonts.

Example of loading a font file automatically according to its file extension, then adding it as a theme override to a Label node:

  1. var path = "/path/to/font.ttf"
  2. var path_lower = path.to_lower()
  3. var font_file = FontFile.new()
  4. if (
  5. path_lower.ends_with(".ttf")
  6. or path_lower.ends_with(".otf")
  7. or path_lower.ends_with(".woff")
  8. or path_lower.ends_with(".woff2")
  9. or path_lower.ends_with(".pfb")
  10. or path_lower.ends_with(".pfm")
  11. ):
  12. font_file.load_dynamic_font(path)
  13. elif path_lower.ends_with(".fnt") or path_lower.ends_with(".font"):
  14. font_file.load_bitmap_font(path)
  15. else:
  16. push_error("Invalid font file format.")
  17. if not font_file.data.is_empty():
  18. # If font was loaded successfully, add it as a theme override.
  19. $Label.add_theme_font_override("font", font_file)

ZIP archives

Godot supports reading and writing ZIP archives using the ZIPReader and ZIPPacker classes. This supports any ZIP file, including files generated by Godot’s “Export PCK/ZIP” functionality (although these will contain imported Godot resources rather than the original project files).

Note

Use ProjectSettings.load_resource_pack to load PCK or ZIP files exported by Godot as additional data packs. That approach is preferred for DLCs, as it makes interacting with additional data packs seamless (virtual filesystem).

This ZIP archive support can be combined with runtime image, 3D scene and audio loading to provide a seamless modding experience without requiring users to go through the Godot editor to generate PCK/ZIP files.

Example that lists files in a ZIP archive in an ItemList node, then writes contents read from it to a new ZIP archive (essentially duplicating the archive):

  1. # Load an existing ZIP archive.
  2. var zip_reader = ZIPReader.new()
  3. zip_reader.open(path)
  4. var files = zip_reader.get_files()
  5. # The list of files isn't sorted by default. Sort it for more consistent processing.
  6. files.sort()
  7. for file in files:
  8. $ItemList.add_item(file, null)
  9. # Make folders disabled in the list.
  10. $ItemList.set_item_disabled(-1, file.ends_with("/"))
  11. # Save a new ZIP archive.
  12. var zip_packer = ZIPPacker.new()
  13. var error = zip_packer.open(path)
  14. if error != OK:
  15. push_error("Couldn't open path for saving ZIP archive (error code: %s)." % error_string(error))
  16. return
  17. # Reuse the above ZIPReader instance to read files from an existing ZIP archive.
  18. for file in zip_reader.get_files():
  19. zip_packer.start_file(file)
  20. zip_packer.write_file(zip_reader.read_file(file))
  21. zip_packer.close_file()
  22. zip_packer.close()

User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next