Question: When should you use preload in Godot?


preload() is a function in Godot that is used for loading a resource when the game starts, before any scripts are run. This can be useful for resources that will be used immediately and frequently throughout your game to eliminate delays caused by loading them on-demand.

Here's when to use preload():

  1. Initialization: When you need a resource to be available as soon as the node or scene is initialized, such as essential textures, sounds, or scripts.

  2. Performance: To avoid hiccups or lag during gameplay, which can occur if resources are loaded while the game is running. Preloading allows you to load resources during a loading screen or the game's startup.

  3. Dependencies: If you have scripts or scenes that rely on certain resources to function correctly from the start, preload() ensures that these dependencies are met before anything tries to use them.

An example of using preload() would look like this:

extends Node # Preload a scene to instantiate it later var my_scene = preload("res://path/to/scene.tscn") func _ready(): # The scene can be instanced immediately without delay var instance_of_scene = my_scene.instance() add_child(instance_of_scene)

However, you should not use preload() for:

  1. Large Resources: If the resource is large and not needed immediately, preloading could lead to longer initial loading times.

  2. Infrequently Used Resources: Resources that are rarely used or needed only under specific conditions should be loaded with load() instead.

  3. Dynamic Resources: When dealing with resources that may change during gameplay or that you want more control over when they're loaded and unloaded.

If you find yourself needing to dynamically load resources, consider using load() or ResourceLoader.load():

extends Node func _ready(): # Load the resource asynchronously if it might cause a delay var my_resource = ResourceLoader.load("res://path/to/resource.ext")

In conclusion, use preload() when you require resources to be available immediately and consistently throughout your game or when optimizing performance is crucial. For dynamic or occasional resource needs, opt for load() or the resource loader methods.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.