How to get the relative path to current folder/script?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Tybobobo
:warning: Old Version Published before Godot 3 was released.

I am attempting to find the current folder path to a specific script (or node).

I am not looking for Node’s get_path(), as that return a NodePath; path to a node. I am looking for the file path. ex: “res://path/to/folder/”.

Anyone know how I may get this path without having to hardcode the res://path/to ?

The reason I want this is because I am working on creating a scene that can be easily imported into other game projects; so the res://path may change depending on project.

Help would be appreciated.

:bust_in_silhouette: Reply From: atze

The only thing I could find is Recource.get_path() which works for everything that is inherited by Resource. (e.g. Script, see 1 for a full list).

After learning about the Resource inheritance, I managed to find the path by using the running scripts path. (Since Script inherits Resource)

var dir = self.get_script().get_path()
dir = str(dir).replace("", "commands/") # replacing with the folder path is where this is run.
commands/ is the folder I was trying to get a path to.


Tybobobo | 2016-06-13 12:13

I found this useful, and I will add a remark to this for anyone else coming along.

You don’t have to parse the string, there is a String.get_base_dir() method that does this.


avencherus | 2016-11-11 19:08

:bust_in_silhouette: Reply From: kakoeimon

I do not know how to get the path but keep in mind that the script knows his path.
For example, let’s say that you have a script in "res://instances/" and a bullet.scn in "res://instances/bullet.scn"
You can call bullet.scn from the like this :

The second way is the what you want.
You can use all the known ways to navigate where you want. If bullet.scn was in "res://bullets/bullet.scn" you can call it like that

This only works for me if I use load. With preload it gives me “Parser Error: Can’t preload resource at path: …” even if the path it spits out is correct. I only tried this with scenes, not other resources. Not sure why it happens.

Edit: Nevermind, loading didn’t work either, the scene had some broken dependencies. fixed those and now both work as described.

markopolo | 2017-07-04 18:43

This just works, pick this as the best answer, you don’t need any parsing.
I’ve tested it on, Windows Debug and Windows Release.

sairam123 | 2021-07-07 15:17

:bust_in_silhouette: Reply From: takaturre

Just to clarify, if you want the resource path of a instanced scene, you can simply use Node.filename. It works if the node actually ‘represents’ a scene loaded from a file - see Node.filename. This (part of the) question was also recently answered here.