Skip to content

Commit 62d5d6c

Browse files
authored
Merge pull request godotengine#8852 from 31/dev/31/singleton-cs
singletons_autoload.rst: add C# example similar to "Global Variable"
2 parents dedb444 + a4e958c commit 62d5d6c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

tutorials/scripting/singletons_autoload.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,33 @@ be accessed directly in GDScript, without requiring ``get_node()``:
9494

9595
PlayerVariables.health -= 10
9696

97+
The **Enable** column has no effect in C# code. However, if the singleton is a
98+
C# script, a similar effect can be achieved by including a static property
99+
called ``Instance`` and assigning it in ``_Ready()``:
100+
101+
.. tabs::
102+
.. code-tab:: csharp
103+
104+
public partial class PlayerVariables : Node
105+
{
106+
public static PlayerVariables Instance { get; private set; }
107+
108+
public int Health { get; set; }
109+
110+
public override void _Ready()
111+
{
112+
Instance = this;
113+
}
114+
}
115+
116+
This allows the singleton to be accessed from C# code without ``GetNode()`` and
117+
without a typecast:
118+
119+
.. tabs::
120+
.. code-tab:: csharp
121+
122+
PlayerVariables.Instance.Health -= 10;
123+
97124
Note that autoload objects (scripts and/or scenes) are accessed just like any
98125
other node in the scene tree. In fact, if you look at the running scene tree,
99126
you'll see the autoloaded nodes appear:

0 commit comments

Comments
 (0)