Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

C# 全局类

Global classes (also known as named scripts) are types registered in Godot's editor so they can be used more conveniently.

  • Global classes show up in the Add Node and Create Resource dialogs.

  • If an exported property is a global class, the inspector restricts assignment, allowing only instances of that global class or any derived classes.

Global classes are registered with the [GlobalClass] attribute.

using Godot;

[GlobalClass]
public partial class MyNode : Node
{
}

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

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

The Select a Node window for the MyNode exported property filters the list of nodes in the scene to match the assignment restriction.

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

If a custom type isn't registered as a global class, the assignment is restricted to the Godot type the custom type is based on. For example, inspector assignments to an export of the type MySimpleSprite2D are restricted to Sprite2D and derived types.

public partial class MySimpleSprite2D : Sprite2D
{
}

When combined with the [GlobalClass] attribute, the [Icon] attribute allows providing a path to an icon to show when the class is displayed in the editor.

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