C# global classes

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#.

  • 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.

  1. using Godot;
  2. [GlobalClass]
  3. public partial class MyNode : Node
  4. {
  5. }

Warning

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.

The MyNode type will be registered as a global class with the same name as the type’s name.

../../../_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.

  1. public partial class Main : Node
  2. {
  3. [Export]
  4. public MyNode MyNode { get; set; }
  5. }

../../../_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.

  1. public partial class MySimpleSprite2D : Sprite2D
  2. {
  3. }

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.

  1. using Godot;
  2. [GlobalClass, Icon("res://Stats/StatsIcon.svg")]
  3. public partial class Stats : Resource
  4. {
  5. [Export]
  6. public int Strength { get; set; }
  7. [Export]
  8. public int Defense { get; set; }
  9. [Export]
  10. public int Speed { get; set; }
  11. }

../../../_images/globalclasses_createresource.webp

The Stats class is a custom resource registered as a global class. Exporting properties of the type Stats will only allow instances of this resource type to be assigned, and the inspector will let you create and load instances of this type easily.

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

Warning

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.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next