Accessing variables from different scripts

Godot Version

godot-4

Question

i have trouble accessing variables from different scripts. the scene the script is in will be enabled in runtime so i cant really use signals and using a global variable would be a bad practice since i am planning on making a lot of such variables later on. i heard there was a way to use a function to sync data but i only found resources for GDscript. i am very confused, please help.

You have to be a little more specific as to what you’re trying to achieve.

There are plenty of ways to get a reference to a class instance at runtime:

What do you mean by this; can you elaborate?


I need a better description of what your problem is in order to help you solve it.

2 Likes

Hi @sabadiasamidze45, for the multiple variables, you can easily use a built-in feature of Godot.

@Sweatix has already given nice options, but I would like to expand on the “singleton” one. In C#, for example, we can create a traditional singleton using the built-in Lazy <T>, but you can also create a singleton using Godot’s built-in AutoLoad feature, in this case you can set up a C# class or use a scene (that uses a C# class) to be your “central” place of variables.

Example from Docs:

public partial class PlayerVariables : Node
{
    public static PlayerVariables Instance { get; private set; }

    public int Health { get; set; }

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

Accessing/using the variable from C#:

PlayerVariables.Instance.Health -= 10;

To autoload a scene/C# class, go to Project > Project Settings > Globals > Autoload.

More info here:
Singletons (Autoload) — Godot Engine (stable) documentation in English

How many global variables? I’m not sure what the upper limit is but that’s what I use in my pixel art games.

@pdhales72 This question does not adhere to, or assist in the understanding of, the topic at hand. If you want help with your question, please create a new topic – preferably with a description that goes beyond the question of “how many global variables?”.

@Sweatix Apologies, I should have phrased my question differently.

1 Like

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