如何在场景的 C# 代码中访问我在 AutoLoad 脚本中创建的单例? (戈多 3)

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

所以我使用的是 Godot 3 的 Mono 版本。我的脚本是用 C# 编写的。我正在尝试按照本教程进行操作:http://docs.godotengine.org/en/latest/getting_started/step_by_step/singletons_autoload.html

但是代码在 GDScript 中,我对它进行的最大尝试都没有成功。我已经正确编译了脚本(必须将它们添加到我的 .csproj),但我似乎无法访问我在 TitleScene.cs Global.cs [=20] 中设置的 PlayerVars 对象=]

Global.cs 配置为自动加载 使用系统; 使用 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一个class来存储变量。

public class PlayerVars {
  public int total;
}

TitleScene.cs - 附上我的默认场景:

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);
    }
}

我觉得自己做错了什么。有什么想法吗?

好的,明白了。

您在项目属性的这个屏幕上通过您给它的名称引用该节点:

在我的例子中是 global

所以现在我的 Global.cs 看起来像这样:

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;
  }

}

我的 TitleScene.cs 看起来像这样:

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);
  }

}