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

Jay*_*ill 4 c# mono godot

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

但代码是用 GDScript 编写的,我对其进行的最佳尝试均未成功。我已经正确编译了脚本(必须将它们添加到我的.csproj),但我似乎无法访问我Global.cs在中设置的 PlayerVars 对象TitleScene.cs

Global.cs配置为自动加载使用系统;使用戈多;

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

}
Run Code Online (Sandbox Code Playgroud)

PlayerVars.cs存储变量的类。

public class PlayerVars {
  public int total;
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我觉得我正在做一些明显错误的事情。有任何想法吗?

Jay*_*ill 7

好吧,想通了。

您可以通过项目属性中在此屏幕上指定的名称来引用该节点:

属性屏幕

就我而言,是的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;
  }

}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)