Are relative paths available for ResourceLoader.Load? Like preload?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By rakkarage

issue talking about relative paths

Ah, ok. It works if the path is not relative or it’s relative, but
prefixed with res:// Preload works with relative paths either way.

var x = load(“not/relative/”) #=> success var x =
load(“…/relative/”) #=> null var x =
load(“res://…/relative/”) #=> success var x =
preload(“…/relative/”) #=> success var x =
preload(“res://…/relative/”) #=> success

excuse my ignorance but i am new
it seems like relative paths could be useful
is there a way to use relative paths in csharp?
i tried all these permutations but none seem to work…

Stream = ResourceLoader.Load<AudioStream>("res://Intro/PinDrop.wav")

then this folder with the script and wav in it would not break when moved or renamed right?


:bust_in_silhouette: Reply From: Zylann

Relative paths don’t work with load or ResourceLoader.Load because contrary to preload (which is specific to GDScript and deduced at compile time), the former does not have any info from where it runs, and so cannot do a relative path lookup. C# itself doesn’t know this either. See load() does not work with relative path using ".." and without "res://" · Issue #5999 · godotengine/godot · GitHub

I know in GDScript it’s possible to still use the path of the script, which then you would append to a relative path to form an absolute path, which works like this:

load(get_script().resource_path.base_dir() + "/relative_path/resource.png")

Which in C# would maybe become:

ResourceLoader.Load<AudioStream>(((Resource)GetScript()).ResourcePath + "/relative_path/resource.png")

You could likely write an extension method to Godot.Object so that Load is always available anywhere with relative paths? But ResourceLoader is a separate class so it cannot do that automatically.

But otherwise you really have to input full paths. Note that it’s actually recommended you export resource properties, rather than hardcoding them. If you do this, Godot will automatically reassign the path if you move the asset from the editor.

In GDScript it’s more common to hardcode script paths because it is the only way to access other script classes (unless they use class_name), but C# classes are all named so it doesn’t have this problem.

:bust_in_silhouette: Reply From: Aristonaut

You’ll have to roll your own load function that does compile-time-relative paths.

It’s a touch tricky. I wrote up a sample Gist that you can tweak to fit your needs. It uses the CSharp attribute [CallerFilePath] to figure out paths. Read up on it, if you are unfamiliar, or you could shoot yourself in the foot.

Sample usage:

IO.Load<Texture>("./icon.png"); //< secret second param filled with this file's path

Anyway, here’s the gist: