Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a singleton I created in my AutoLoad script in a scene's C# code? (Godot 3)

Tags:

c#

mono

godot

So I'm using the Mono version of Godot 3. My scripts are in C#. I'm attempting to follow this tutorial: http://docs.godotengine.org/en/latest/getting_started/step_by_step/singletons_autoload.html

But the code is in GDScript and my best attempts to adapt it have been unsuccessful. I've got the scripts compiling correctly (had to add them to my .csproj) but I just can't seem to access the PlayerVars object I set in Global.cs in TitleScene.cs

Global.cs Configured as an Autoload using System; using Godot;

public class Global : Node {

  private PlayerVars playerVars;

  public override void _Ready () {
    this.playerVars = new PlayerVars();
    int total = 5;
    Godot.GD.Print(what: "total is " + total);
    this.playerVars.total = total;
    GetNode("/root/").Set("playerVars",this.playerVars);
  }

}

PlayerVars.cs A class to store variables.

public class PlayerVars {
  public int total;
}

TitleScene.cs - Attached to my default scene:

using System;
using Godot;

public class TitleScene : Node {

    public override void _Ready () {
        Node playervars = (Node) GetNode("/root/playerVars");
        Godot.GD.Print("total in titlescene is" + playervars.total);
    }
}

I feel like I'm doing something obvious wrong. Any ideas?

like image 555
Jaybill Avatar asked Oct 25 '25 23:10

Jaybill


1 Answers

Okay, figured it out.

You reference the node by the name you give it on this screen in Project Properties:

properties screen

In my case it was global.

So now my Global.cs looks like this:

using System;
using Godot;

public class Global : Node
{

  private PlayerVars playerVars;

  public override void _Ready()
  {
    // Called every time the node is added to the scene.
    // Initialization here
    Summator summator = new Summator();
    playerVars = new PlayerVars();

    playerVars.total = 5;

    Godot.GD.Print(what: "total is " + playerVars.total);

  }

  public PlayerVars GetPlayerVars(){
    return playerVars;
  }

}

And my TitleScene.cs looks like this:

using System;
using Godot;

public class TitleScene : Node
{

  public override void _Ready()
  {
    // Must be cast to the Global type we derived from Node earlier to
    // use its custom methods and props
    Global global = (Global) GetNode("/root/global");
    Godot.GD.Print(global.GetPlayerVars().total);
  }

}
like image 155
Jaybill Avatar answered Oct 27 '25 11:10

Jaybill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!