Resource in Godot – Complete Guide

Godot Engine is a powerful open-source tool for game developers, and mastering its components is key to creating sophisticated and engaging games. Today, we’ll delve deep into one of its fundamental elements: the Resource class in Godot 4. Understanding how to harness the power of resources will streamline your game development process, allowing you to create, manage, and optimize game assets effectively.

What are Resources in Godot?

Resources are the backbone of any Godot project; they are a special kind of object designed to hold data. Every asset in Godot, whether it’s a script, a texture, or an audio file, is considered a resource. They are unique as they can be shared between scenes and instances, making your game more memory-efficient and your workflow more seamless.

What are Resources Used For?

These objects are incredibly versatile. They can be anything from a simple image that your game character holds to a complex animation sequence that drives your main character’s actions. By understanding resources, you can better manage the numerous assets that bring your game to life. A resource can be instantiated, duplicated, and even stored on disk for use across multiple projects.

Why Should I Learn About Resources?

Learning about resources in Godot is crucial for any aspiring game developer. It allows for smart asset management, reducing the memory footprint of games by reusing assets. Additionally, it provides a foundation for understanding how Godot handles data, setting you up for more advanced topics. Mastery over resources can significantly boost the efficiency of your development process, helping you build better games faster.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating and Using Resources

Let’s start by creating a simple resource in Godot. This can be done by extending the Resource class. Here’s an example of a custom resource for a game character’s stats:

extends Resource
class_name CharacterStats

export (int) var health = 100
export (int) var energy = 100
export (int) var strength = 10
export (int) var agility = 10

This CharacterStats resource can now hold important data for a character. To use this in your game, you can create an instance of the resource and attach it to a character object:

var stats = CharacterStats.new()
$Character.stats = stats

Here is how to load the resource from a file if you have saved it previously or exported it to a .tres or .res file:

var stats = preload("res://CharacterStats.tres").new()
$Character.stats = stats

Modifying Resource Properties

Once you’ve created a resource and attached it to an object, you can easily modify its properties using the editor or through code:

# Using code to adjust health
$Character.stats.health -= 20

# Increasing strength
$Character.stats.strength += 5

Type-safe access to these properties ensures that you are modifying what you intend to, providing cleaner and more maintainable code.

Saving and Loading Resources

Saving resources to disk allows you to reuse them in various parts of your game. You can save the modified resource as follows:

var resource_saver = ResourceSaver.new()
var stats = $Character.stats
resource_saver.save("res://CharacterStatsModified.tres", stats)

And loading them back into your game is just as easy:

var resource_loader = ResourceLoader.new()
var stats = resource_loader.load("res://CharacterStatsModified.tres")
$Character.stats = stats

By using the ResourceLoader and ResourceSaver classes, Godot provides a streamlined process for managing resources within your game.

Duplicating Resources

Duplicating resources is particularly useful when you need a unique instance of a resource. You can duplicate a resource and then modify the duplicate without affecting the original. Here’s how:

var original_stats = $Character.stats
var duplicate_stats = original_stats.duplicate()
duplicate_stats.health = 150 # This will not change original_stats health

This ensures that you can create variations of a single resource, making your game design process flexible and efficient.

The concept of resources in Godot is a powerful feature that, once understood and utilized effectively, can greatly enhance your game development workflow.

In Godot, the Resource class also allows for more complex operations, like setting up signals or changing resource properties when certain conditions are met. These advanced techniques can elevate game functionalities and provide dynamic interactions. Consider a scenario where your character recovers health over time:

# Signal emitted when the character heals
class_name CharacterStats extends Resource
signal character_healed(amount)

# Function to recover health over time
func recover_health(delta):
    health += delta
    emit_signal("character_healed", delta)

By connecting to the “character_healed” signal, other parts of your game can respond to the character’s health recovery:

# Connect the 'character_healed' signal to a function in another node
$Character.stats.connect("character_healed", self, "_on_character_healed")

# Function that responds to the character healing
func _on_character_healed(amount):
    print("Character healed by ", amount)

Another important feature of Godot’s Resource class is its support for serialization and deserialization. This enables resources to be written to or read from a string in various formats, such as JSON:

# Save resource state to JSON string
func save_to_json(resource):
    return JSON.print(resource.to_dict())

# Load resource state from JSON string
func load_from_json(json_string):
    var dict = JSON.parse(json_string).result
    var resource = CharacterStats.new()
    resource.from_dict(dict)
    return resource

When working with multiple instances that share the same resource, you might want to ensure that changes to one instance don’t affect others. Godot allows you to do this by making a “deep-copy” of the resource:

# Make a deep copy (duplicate) and ensure no shared sub-resources
var deep_duplicate_stats = original_recource.duplicate(true)

By setting the deep parameter to true, all of the sub-resources will be duplicated along with the main resource, making sure that changes to one instance don’t affect another.

Resources also play a crucial role in localization. For example, you can store multilingual text in a resource and retrieve it based on the player’s language setting:

# LocalizedStrings is a custom resource that contains a dictionary of text translations
var localized_strings = LocalizedStrings.new()

# Function to retrieve a localized string
func get_localized_text(key, language):
    return localized_strings.strings[language][key]

# Usage
var hello_text = get_localized_text("hello", "EN")

Lastly, conditional loading of resources can optimize how your game runs. For instance, if a resource is not needed immediately, you can defer its loading to a more appropriate time, such as between levels or during a loading screen:

# PoolStringArray of resources to load
var resources_to_load = PoolStringArray(["res://enemy.tres", "res://weapon.tres"])

# Deferred loading function
func load_resources_deferred():
    for resource_path in resources_to_load:
        var resource = ResourceLoader.load(resource_path)
        # Further processing of the loaded resource

Through the use of Godot’s powerful Resource class, you can effectively manage a plethora of game assets, making your development process both more efficient and more modular. We’ve shown several practical applications of resources that can enhance your game, and we encourage you to dive in and experiment further as you create your dream game projects with us at Zenva.

Resources play a significant role in the design and efficiency of Godot’s scene system. Below are various ways that demonstrate how you can leverage resources in different game development scenarios:

Scriptable Objects: Create scriptable objects in Godot which act similarly to those in Unity. These are resources that contain data you can use to define behavior or properties within your game without needing a node:

# Define a scriptable object for a weapon
extends Resource
class_name WeaponData

export(String) var name = "Unnamed Weapon"
export(float) var damage = 10.0
export(Texture) var icon = null

By attaching this WeaponData resource to a node acting as a weapon, you can easily define and modify the weapon’s characteristics in the editor or during runtime:

var weapon = WeaponData.new()
weapon.name = "Sword of Truth"
weapon.damage = 15.0

# Assign the resource to a node
$WeaponHolder.weapon_data = weapon

Sometimes, you may want to create universal properties that aren’t tied to a particular instance, like game settings. Resources are perfect for this scenario:

# Create a GameSettings resource
extends Resource
class_name GameSettings

export(bool) var fullscreen = false
export(int) var resolution_x = 1920
export(int) var resolution_y = 1080
export(int) var graphics_quality = 2

You can define a singleton that holds these settings, enabling you to access them from anywhere in your project:

# Load the GameSettings resource and apply them
var settings = preload("res://GameSettings.tres")
OS.window_fullscreen = settings.fullscreen
OS.set_window_size(Vector2(settings.resolution_x, settings.resolution_y))
# Any other settings you wish to apply...

Animations are another type of resource in Godot. By creating an Animation resource, you manage animations more flexibly. Here’s an example:

# Create an Animation resource
var walk_animation = Animation.new()

# Set up animation properties
walk_animation.set_length(1.0)
walk_animation.loop = true

# Add tracks to the animation
var track_index = walk_animation.add_track(Animation.TYPE_VALUE)
walk_animation.track_set_path(track_index, "Node2D/position")
walk_animation.track_insert_key(track_index, 0.0, Vector2(0,0))
walk_animation.track_insert_key(track_index, 1.0, Vector2(100,0))

# Assign the animation to an AnimationPlayer
$AnimationPlayer.add_animation("walk", walk_animation)

Godot’s flexible Resource system even allows for creating custom shaders that can be applied to multiple objects. These shaders are resources you can tweak and reuse:

# Create a Shader resource
var shader = Shader.new()

# Write custom shader code
shader.set_code('''
shader_type canvas_item;

void fragment() {
    COLOR = vec4(1.0, 1.0, 1.0, 1.0);
}
''')

# Apply the shader to a ShaderMaterial
var material = ShaderMaterial.new()
material.shader = shader

# Assign the material to a sprite
$Sprite.material = material

Gone are the days of manually setting up materials for every object. With Godot’s resource system, one shader resource can be linked to multiple materials, promoting reusability and consistency throughout your project.

Lastly, consider this common scenario – sound management. Sounds in a game are also resources, and Godot allows you to define them once and play them from anywhere:

# Define a Sound resource
extends Resource
class_name SoundData

export(AudioStream) var audio_stream

# Function to play the sound from any node with an AudioStreamPlayer
func play_sound(player_path):
    var player = get_node(player_path)
    player.stream = audio_stream
    player.play()

By using resources wisely, Godot’s game developers can build games that are easier to maintain, optimize, and expand. We at Zenva understand the critical role of smart resource management in professional game development, and our tutorials are designed to help you leverage resources to their full potential. Whether you’re creating textures, animations, scriptable objects, or shaders, the skillful utilization of Godot’s Resource class is a game-changer in efficient game design and development.

Where to Go Next with Your Godot Journey

Having grasped the fundamentals of the Resource class in Godot 4, you might be wondering, “What’s next?” Your learning journey is just beginning, and there’s a whole universe of game development just waiting to be explored. To continue honing your skills and expanding your knowledge, we invite you to check out our Godot Game Development Mini-Degree. This program dives deep into cross-platform game development, covering a range of topics that will elevate your game creation prowess.

In this Mini-Degree, you’ll learn about everything from 2D and 3D asset creation, gameplay control flow, combat systems, to UI design—all within the versatile Godot engine. Whether you’re a beginner eager to start your game development career, or an advanced developer looking to polish your skills, Zenva’s courses provide a structured yet flexible path to help you reach your goals.

If you’re looking for a broader selection of Godot content, we’ve got an array of Godot courses suited for every level. With over 250 supported courses, from coding basics to advanced game mechanics, Zenva offers the tools to convert your creativity into tangible game projects. Remember, your journey in game development is unique, and with Zenva, you can go from beginner to professional at your own pace, and on your own schedule.

Conclusion

To sum up, understanding and utilizing the Resource class in Godot 4 is a key step towards becoming a proficient game developer. Whether you’re crafting rich environments, intricate characters, or complex gameplay mechanics, resources are the building blocks that bring your creative visions to life. They empower you to manage your game’s assets efficiently and create more dynamic, engaging experiences for players. Remember, what you’ve learned today is just the tip of the iceberg in the vast, exciting world of game development with Godot.

Here at Zenva, we’re dedicated to guiding you through every aspect of game creation. Our Godot Game Development Mini-Degree is the perfect next step to further enhance your understanding and mastery of game development with Godot. So why wait? Take the leap, and let’s continue this incredible journey together, creating the games we love to play and share with the world.

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.