代码之家  ›  专栏  ›  技术社区  ›  Jaybill

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

  •  2
  • Jaybill  · 技术社区  · 7 年前

    所以我用的是Godot 3的单声道版本。我的脚本是C语言。我正在尝试学习本教程: http://docs.godotengine.org/en/latest/getting_started/step_by_step/singletons_autoload.html

    但是代码在GDScript中,我对其进行的最佳调整都没有成功。我已经正确编译了脚本(必须将它们添加到我的 .csproj )但我似乎无法访问我设置的PlayerVars对象 Global.cs 在里面 TitleScene.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 存储变量的类。

    public class PlayerVars {
      public int total;
    }
    

    标题新世。反恐精英 -附加到默认场景:

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

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

    1 回复  |  直到 7 年前
        1
  •  3
  •   Jaybill    7 年前

    好吧,我想出来了。

    通过在此屏幕上在“项目属性”中指定的名称引用节点:

    properties screen

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