C# 全局类

Global classes (also known as named scripts) are types registered in Godot's editor so they can be used more conveniently. In GDScript, this is achieved using the class_name keyword at the top of a script. This page describes how to achieve the same effect in C#.

  • 全局类显示在添加节点创建资源对话框中。

  • 如果导出属性是全局类,则检查器会限制赋值,只允许该全局类或任何派生类的实例。

全局类使用 [GlobalClass] 属性注册。

using Godot;

[GlobalClass]
public partial class MyNode : Node
{
}

警告

The file name must match the class name in case-sensitive fashion. For example, a global class named "MyNode" must have a file name of MyNode.cs, not myNode.cs.

MyNode 类型将被注册为一个全局类,其名称与类型的名称相同。

../../../_images/globalclasses_addnode.webp

MyNode 导出属性的选择节点窗口会过滤场景中的节点列表以匹配赋值限制。

public partial class Main : Node
{
    [Export]
    public MyNode MyNode { get; set; }
}
../../../_images/globalclasses_exportednode.webp

如果自定义类型未被注册为全局类,则赋值被限制为自定义类型所基于的 Godot 类型。例如,MySimpleSprite2D 类型的导出变量的检查器赋值,将被限制为Sprite2D及其派生类型。

public partial class MySimpleSprite2D : Sprite2D
{
}

当与 [GlobalClass] 属性结合时,[Icon] 属性允许提供该类被显示在编辑器中时要显示的图标的路径。

using Godot;

[GlobalClass, Icon("res://Stats/StatsIcon.svg")]
public partial class Stats : Resource
{
    [Export]
    public int Strength { get; set; }

    [Export]
    public int Defense { get; set; }

    [Export]
    public int Speed { get; set; }
}
../../../_images/globalclasses_createresource.webp

Stats 类是一个注册为全局类的自定义资源。导出属性 类型为 Stats 的属性将仅允许分配此资源类型的实例,并且检查器将允许你轻松创建和加载此类型的实例。

../../../_images/globalclasses_exportedproperty1.webp ../../../_images/globalclasses_exportedproperty2.webp

警告

The Godot editor will hide these custom classes with names that begin with the prefix "Editor" in the "Create New Node" or "Create New Scene" dialog windows. The classes are available for instantiation at runtime via their class names, but are automatically hidden by the editor windows along with the built-in editor nodes used by the Godot editor.