How to access an Autoload from a resource in C#?

Godot Version

4.2.stable.mono

Question

Alrighty, so I have a resource class which needs to access a autoload. However the only way I’ve seen so far is doing

var global = GetNode<Global>("/root/Global");

however resources aren’t a part of the tree, and as such they can’t do it this way, but in GDscript resources are able to use autoloads. So is there a way to do this?
I tried a solution where we just create a variable then the node which’ll use the resource will give it a refrence to the autoload to that variable. but it didn’t work since it was of type Node which dosen’t have all the things I try use from the Autoload.

Help will be highly appriciated!

1 Like

If the Enabled checkbox is checked (it is checked by default) then you do not need to use get node and can just reference the singleton directly by the name you have given it in the Name column in project settings:

In your example, if the singleton is called Global (very on the nose):

Global.SomeFunctionNameWithDisgustingCamelCase

For example, in my scene given screenshot above:

func _ready():
    Events.player_leveled_up.connect(my_awesome_method_name)
    # or 
    var weapon_upgrades = UpgradesDB.upgrades.filter(filter_upgrades_for_weapon)

This is specified in the docs here if you wanted more info: Singletons (Autoload) — Godot Engine (latest) documentation in English

That’s how I expected it to work with C# but it throws an error when I try access it like that, the docs recomend using get node to retrive the autoload from the tree, but since my class is a resource it can’t do that.

1 Like