Autoload scripts C#

Godot Version

4.2 Mono

Question

I have a C# script that I load in Project Settings → Autoload, however I don’t understand how to access its variables from other scripts. Help

using Godot;

public partial class GameManager : Node
{
    public int CurrentMoney {get; set;} = 0;
    public int CurrentExperience {get; set;} = 0;
}
1 Like

In another script, to gain access use:

public GameManager gameManager {get; set;} //  New Variable
public override void _Ready()
{
    gameManager = GetNodeOrNull("/root/GameManager") as GameManager;
}
1 Like

Thank you, kind man.

1 Like

Oh you’re welcome, check the documentation more often.

1 Like

This is one way, however, another even easier way is to create a singleton.

The most simple way to do this is by doing the following:

public static GameManager Instance;

public override void _Ready()
{
	base._Ready();
	Instance ??= this;
}

If you do this, you can simply do

GameManager.Something

Without having to get it’s reference and cast it every single time.

Obviously this is only good if you WANT a singleton but here you go :slight_smile:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.