Up to date
This page is up to date for Godot 4.3.
If you still find outdated information, please open an issue.
Chargement et sauvegarde des fichiers d'exécution
Voir aussi
See L'enregistrement des parties 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.
Avertissement
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 Processus d’importation for details.
Voir aussi
You can see how saving and loading works in action using the Run-time File Saving and Loading (Serialization) demo project.
Texte brut et fichiers binaires
Godot's FileAccess class provides methods to access files on the filesystem for reading and writing:
func save_file(content):
var file = FileAccess.open("/path/to/file.txt", FileAccess.WRITE)
file.store_string(content)
func load_file():
var file = FileAccess.open("/path/to/file.txt", FileAccess.READ)
var content = file.get_as_text()
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 API de sérialisation binaire.
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:
Plusieurs formats d'image peuvent également être enregistrés par Godot lors de l'exécution en utilisant les méthodes suivantes :
Image.save_exr or Image.save_exr_to_buffer (only available in editor builds, cannot be used in exported projects)
Les méthodes avec le suffixe to_buffer enregistrent l'image dans un PackedByteArray au lieu d'utiliser un fichier. Ceci est utile pour envoyer l'image sur le réseau ou dans une archive ZIP sans avoir à l'écrire sur le système de fichiers. Cela peut augmenter les performances en réduisant l'utilisation des I/O.
Note
Si vous affichez l'image chargée sur une surface 3D, assurez-vous d'appeler Image.generate_mipmaps afin que la texture ne semble pas granuleuse lorsqu'elle est vue de loin. Cela est également utile en 2D lorsque vous suivez les instructions sur la réduction de l'aliasing lors de la réduction de la résolution.
Exemple de chargement d'une image et de son affichage dans un nœud TextureRect (ce qui nécessite une conversion en ImageTexture) :
# Load an image of any format supported by Godot from the filesystem.
var image = Image.load_from_file(path)
# Optionally, generate mipmaps if displaying the texture on a 3D surface
# so that the texture doesn't look grainy when viewed at a distance.
#image.generate_mipmaps()
$TextureRect.texture = ImageTexture.create_from_image(image)
# Save the loaded Image to a PNG image.
image.save_png("/path/to/file.png")
# Save the converted ImageTexture to a PNG image.
$TextureRect.texture.get_image().save_png("/path/to/file.png")
Fichiers audio/vidéo
Godot prend en charge le chargement audio Ogg Vorbis à l'exécution. Notez que tous les fichiers avec une extension .ogg ne sont pas forcément des fichiers Ogg Vorbis. Certains peuvent être des vidéos Ogg Theora, ou contenir de l'audio Opus dans un conteneur Ogg. Ces fichiers ne se chargeront pas correctement en tant que fichiers audio dans Godot.
Exemple de chargement d'un fichier audio Ogg Vorbis dans un nœud AudioStreamPlayer :
$AudioStreamPlayer.stream = AudioStreamOggVorbis.load_from_file(path)
Exemple de chargement d'un fichier vidéo Ogg Theora dans un nœud VideoStreamPlayer:
var video_stream_theora = VideoStreamTheora.new()
# File extension is ignored, so it is possible to load Ogg Theora videos
# that have an `.ogg` extension this way.
video_stream_theora.file = "/path/to/file.ogv"
$VideoStreamPlayer.stream = video_stream_theora
# VideoStreamPlayer's Autoplay property won't work if the stream is empty
# before this property is set, so call `play()` after setting `stream`.
$VideoStreamPlayer.play()
Note
Godot ne prend pas encore en charge le chargement en temps réel des fichiers MP3 ou WAV. En attendant que cela soit implémenté, il est possible de mettre en œuvre le chargement en temps réel des fichiers WAV en utilisant un script, car la propriété data de AudioStreamWAV est exposée aux scripts.
Il est toujours possible de sauvegarder des fichiers WAV en utilisant AudioStreamWAV.save_to_wav, ce qui est utile pour l'audio généré de manière procédurale ou les enregistrements de microphone.
des scènes 3D
Godot prend en charge nativement glTF 2.0, à la fois dans l'éditeur et dans les projets exportés. En utilisant GLTFDocument et GLTFState ensemble, Godot peut charger et sauvegarder des fichiers glTF dans les projets exportés, aux formats texte (.gltf) et binaire (.glb). Le format binaire est à privilégier car il est plus rapide à écrire et plus compact, mais le format texte est plus facile à déboguer.
Exemple de chargement d'une scène glTF et d'ajout de son nœud racine à la scène :
# Load an existing glTF scene.
# GLTFState is used by GLTFDocument to store the loaded scene's state.
# GLTFDocument is the class that handles actually loading glTF data into a Godot node tree,
# which means it supports glTF features such as lights and cameras.
var gltf_document_load = GLTFDocument.new()
var gltf_state_load = GLTFState.new()
var error = gltf_document_load.append_from_file("/path/to/file.gltf", gltf_state_load)
if error == OK:
var gltf_scene_root_node = gltf_document_load.generate_scene(gltf_state_load)
add_child(gltf_scene_root_node)
else:
show_error("Couldn't load glTF scene (error code: %s)." % error_string(error))
# Save a new glTF scene.
var gltf_document_save := GLTFDocument.new()
var gltf_state_save := GLTFState.new()
gltf_document_save.append_from_scene(gltf_scene_root_node, gltf_state_save)
# The file extension in the output `path` (`.gltf` or `.glb`) determines
# whether the output uses text or binary format.
# `GLTFDocument.generate_buffer()` is also available for saving to memory.
gltf_document_save.write_to_filesystem(gltf_state_save, path)
Note
Lors du chargement d'une scène glTF, un chemin de base doit être défini afin que les ressources externes telles que les textures puissent être chargées correctement. Lors du chargement à partir d'un fichier, le chemin de base est automatiquement défini sur le dossier contenant le fichier. Lors du chargement à partir d'un tampon, ce chemin de base doit être défini manuellement, car Godot ne peut pas inférer ce chemin.
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 Polices du système.
Example of loading a font file automatically according to its file extension, then adding it as a theme override to a Label node:
var path = "/path/to/font.ttf"
var path_lower = path.to_lower()
var font_file = FontFile.new()
if (
path_lower.ends_with(".ttf")
or path_lower.ends_with(".otf")
or path_lower.ends_with(".woff")
or path_lower.ends_with(".woff2")
or path_lower.ends_with(".pfb")
or path_lower.ends_with(".pfm")
):
font_file.load_dynamic_font(path)
elif path_lower.ends_with(".fnt") or path_lower.ends_with(".font"):
font_file.load_bitmap_font(path)
else:
push_error("Invalid font file format.")
if not font_file.data.is_empty():
# If font was loaded successfully, add it as a theme override.
$Label.add_theme_font_override("font", font_file)
Archives ZIP
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):
# Load an existing ZIP archive.
var zip_reader = ZIPReader.new()
zip_reader.open(path)
var files = zip_reader.get_files()
# The list of files isn't sorted by default. Sort it for more consistent processing.
files.sort()
for file in files:
$ItemList.add_item(file, null)
# Make folders disabled in the list.
$ItemList.set_item_disabled(-1, file.ends_with("/"))
# Save a new ZIP archive.
var zip_packer = ZIPPacker.new()
var error = zip_packer.open(path)
if error != OK:
push_error("Couldn't open path for saving ZIP archive (error code: %s)." % error_string(error))
return
# Reuse the above ZIPReader instance to read files from an existing ZIP archive.
for file in zip_reader.get_files():
zip_packer.start_file(file)
zip_packer.write_file(zip_reader.read_file(file))
zip_packer.close_file()
zip_packer.close()