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.
Checking the stable version of the documentation...
C# exports¶
导出简介¶
In Godot, class members can be exported. This means their value gets saved along
with the resource (such as the scene) they're
attached to. They will also be available for editing in the property editor.
Exporting is done by using the [Export]
attribute.
using Godot;
public partial class ExportExample : Node3D
{
[Export]
private int Number = 5;
}
In that example the value 5
will be saved, and after building the current project
it will be visible in the property editor.
导出成员变量的基本好处之一是使它们在编辑器中可见并可编辑. 这样, 美术师和游戏设计师可以修改值, 这些值以后会影响程序的运行方式. 为此, 提供了一种特殊的导出语法.
Exporting can only be done with Variant-compatible types.
备注
Exporting properties can also be done in GDScript, for information on that see GDScript 导出.
Basic use¶
Exporting can work with fields and properties.
[Export]
private int _number;
[Export]
public int Number { get; set; }
Exported members can specify a default value; otherwise, the default value of the type is used instead.
[Export]
private int _number; // Defaults to '0'
[Export]
private string _text; // Defaults to 'null' because it's a reference type
[Export]
private string _greeting = "Hello World"; // Exported field specifies a default value
[Export]
public string Greeting { get; set; } = "Hello World"; // Exported property specifies a default value
// This property uses `_greeting` as its backing field, so the default value
// will be the default value of the `_greeting` field.
[Export]
public string GreetingWithBackingField
{
get => _greeting;
set => _greeting = value;
}
Resources and nodes can be exported.
[Export]
public Resource Resource { get; set; }
[Export]
public Node Node { get; set; }
Grouping exports¶
It is possible to group your exported properties inside the Inspector with the [ExportGroup]
attribute. Every exported property after this attribute will be added to the group. Start a new
group or use [ExportGroup("")]
to break out.
[ExportGroup("My Properties")]
[Export]
public int Number { get; set; } = 3;
The second argument of the attribute can be used to only group properties with the specified prefix.
Groups cannot be nested, use [ExportSubgroup]
to create subgroups within a group.
[ExportSubgroup("Extra Properties")]
[Export]
public string Text { get; set; } = "";
[Export]
public bool Flag { get; set; } = false;
You can also change the name of your main category, or create additional categories in the property
list with the [ExportCategory]
attribute.
[ExportCategory("Main Category")]
[Export]
public int Number { get; set; } = 3;
[Export]
public string Text { get; set; } = "";
[ExportCategory("Extra Category")]
[Export]
private bool Flag { get; set; } = false;
备注
The list of properties is organized based on the class inheritance, and new categories break that expectation. Use them carefully, especially when creating projects for public use.
Strings as paths¶
Property hints can be used to export strings as paths
String as a path to a file.
[Export(PropertyHint.File)]
public string GameFile { get; set; }
String as a path to a directory.
[Export(PropertyHint.Dir)]
public string GameDirectory { get; set; }
String as a path to a file, custom filter provided as hint.
[Export(PropertyHint.File, "*.txt,")]
public string GameFile { get; set; }
Using paths in the global filesystem is also possible, but only in scripts in tool mode.
String as a path to a PNG file in the global filesystem.
[Export(PropertyHint.GlobalFile, "*.png")]
public string ToolImage { get; set; }
String as a path to a directory in the global filesystem.
[Export(PropertyHint.GlobalDir)]
public string ToolDir { get; set; }
The multiline annotation tells the editor to show a large input field for editing over multiple lines.
[Export(PropertyHint.MultilineText)]
public string Text { get; set; }
Limiting editor input ranges¶
Using the range property hint allows you to limit what can be input as a value using the editor.
Allow integer values from 0 to 20.
[Export(PropertyHint.Range, "0,20,")]
public int Number { get; set; }
Allow integer values from -10 to 20.
[Export(PropertyHint.Range, "-10,20,")]
public int Number { get; set; }
Allow floats from -10 to 20 and snap the value to multiples of 0.2.
[Export(PropertyHint.Range, "-10,20,0.2")]
public float Number { get; set; }
If you add the hints "or_greater" and/or "or_less" you can go above or below the limits when adjusting the value by typing it instead of using the slider.
[Export(PropertyHint.Range, "0,100,1,or_greater,or_less")]
public int Number { get; set; }
Floats with easing hint¶
Display a visual representation of the 'ease()' function when editing.
[Export(PropertyHint.ExpEasing)]
public float TransitionSpeed { get; set; }
Colors¶
Regular color given as red-green-blue-alpha value.
[Export]
private Color Color { get; set; }
Color given as red-green-blue value (alpha will always be 1).
[Export(PropertyHint.ColorNoAlpha)]
private Color Color { get; set; }
节点¶
Since Godot 4.0, nodes can be directly exported without having to use NodePaths.
[Export]
public Node Node { get; set; }
Custom node classes can also be used, see C# global classes.
Exporting NodePaths like in Godot 3.x is still possible, in case you need it:
[Export]
private NodePath _nodePath;
public override void _Ready()
{
var node = GetNode(_nodePath);
}
资源¶
[Export]
private Resource Resource;
In the Inspector, you can then drag and drop a resource file from the FileSystem dock into the variable slot.
Opening the inspector dropdown may result in an extremely long list of possible classes to create, however. Therefore, if you specify a type derived from Resource such as:
[Export]
private AnimationNode Resource;
The drop-down menu will be limited to AnimationNode and all its inherited classes. Custom resource classes can also be used, see C# global classes.
必须注意, 即使在编辑器中未运行脚本, 导出的属性仍可编辑. 可以与 使用工具模式的脚本 结合使用.
导出位标志¶
Members whose type is an enum with the [Flags]
attribute can be exported and
their values are limited to the members of the enum type.
The editor will create a widget in the Inspector, allowing to select none, one,
or multiple of the enum members. The value will be stored as an integer.
// Use power of 2 values for the values of the enum members.
[Flags]
public enum MyEnum
{
Fire = 1 << 1,
Water = 1 << 2,
Earth = 1 << 3,
Wind = 1 << 4,
// A combination of flags is also possible.
FireAndWater = Fire | Water,
}
[Export]
public SpellElements MySpellElements { get; set; }
Integers used as bit flags can store multiple true
/false
(boolean)
values in one property. By using the Flags
property hint, they
can be set from the editor.
// Set any of the given flags from the editor.
[Export(PropertyHint.Flags, "Fire,Water,Earth,Wind")]
public int SpellElements { get; set; } = 0;
You must provide a string description for each flag. In this example, Fire
has value 1, Water
has value 2, Earth
has value 4 and Wind
corresponds to value 8. Usually, constants should be defined accordingly (e.g.
private const int ElementWind = 8
and so on).
You can add explicit values using a colon:
[Export(PropertyHint.Flags, "Self:4,Allies:8,Foes:16")]
public int SpellTargets { get; set; } = 0;
Only power of 2 values are valid as bit flags options. The lowest allowed value is 1, as 0 means that nothing is selected. You can also add options that are a combination of other flags:
[Export(PropertyHint.Flags, "Self:4,Allies:8,Self and Allies:12,Foes:16")]
public int SpellTargets { get; set; } = 0;
Export annotations are also provided for the physics and render layers defined in the project settings.
[Export(PropertyHint.Layers2DPhysics)]
public int Layers2DPhysics { get; set; }
[Export(PropertyHint.Layers2DRender)]
public int Layers2DRender { get; set; }
[Export(PropertyHint.Layers3DPhysics)]
public int layers3DPhysics { get; set; }
[Export(PropertyHint.Layers3DRender)]
public int layers3DRender { get; set; }
使用位标志需要对位操作有一定的了解. 如果有疑问, 请使用布尔变量代替.
Exporting enums¶
Members whose type is an enum can be exported and their values are limited to the members of the enum type. The editor will create a widget in the Inspector, enumerating the following as "Thing 1", "Thing 2", "Another Thing". The value will be stored as an integer.
public enum MyEnum
{
Thing1,
Thing2,
AnotherThing = -1,
}
[Export]
public MyEnum MyEnum { get; set; }
Integer and string members can also be limited to a specific list of values using the
[Export]
annotation with the PropertyHint.Enum
hint.
The editor will create a widget in the Inspector, enumerating the following as Warrior,
Magician, Thief. The value will be stored as an integer, corresponding to the index
of the selected option (i.e. 0
, 1
, or 2
).
[Export(PropertyHint.Enum, "Warrior,Magician,Thief")]
public int CharacterClass { get; set; };
You can add explicit values using a colon:
[Export(PropertyHint.Enum, "Slow:30,Average:60,Very Fast:200")]
public int CharacterSpeed { get; set; }
If the type is string
, the value will be stored as a string.
[Export(PropertyHint.Enum, "Rebecca,Mary,Leah")]
public string CharacterName { get; set; }
If you want to set an initial value, you must specify it explicitly:
[Export(PropertyHint.Enum, "Rebecca,Mary,Leah")]
public string CharacterName { get; set; } = "Rebecca";
Exporting collections¶
As explained in the C# Variant documentation, only
certain C# arrays and the collection types defined in the Godot.Collections
namespace are Variant-compatible, therefore, only those types can be exported.
Exporting Godot arrays¶
[Export]
public Godot.Collections.Array Array { get; set; }
Using the generic Godot.Collections.Array<T>
allows to specify the type of the
array elements which will be used as a hint for the editor. The Inspector will
restrict the elements to the specified type.
[Export]
public Godot.Collections.Array<string> Array { get; set; }
The default value of Godot arrays is null, a different default can be specified:
[Export]
public Godot.Collections.Array<string> CharacterNames { get; set; } = new Godot.Collections.Array<string>
{
"Rebecca",
"Mary",
"Leah",
};
Arrays with specified types which inherit from resource can be set by drag-and-dropping multiple files from the FileSystem dock.
[Export]
public Godot.Collections.Array<Texture> Textures { get; set; }
[Export]
public Godot.Collections.Array<PackedScene> Scenes { get; set; }
Exporting Godot dictionaries¶
[Export]
public Godot.Collections.Dictionary Dictionary { get; set; }
Using the generic Godot.Collections.Dictionary<TKey, TValue>
allows to specify
the type of the key and value elements of the dictionary.
备注
Typed dictionaries are currently unsupported in the Godot editor, so the Inspector will not restrict the types that can be assigned, potentially resulting in runtime exceptions.
[Export]
public Godot.Collections.Dictionary<string, int> Dictionary { get; set; }
The default value of Godot dictionaries is null, a different default can be specified:
[Export]
public Godot.Collections.Dictionary<string, int> CharacterLives { get; set; } = new Godot.Collections.Dictionary<string, int>
{
["Rebecca"] = 10,
["Mary"] = 42,
["Leah"] = 0,
};
Exporting C# arrays¶
C# arrays can exported as long as the element type is a Variant-compatible type.
[Export]
public Vector3[] Vectors { get; set; }
[Export]
public NodePath[] NodePaths { get; set; }
The default value of C# arrays is null, a different default can be specified:
[Export]
public Vector3[] Vectors { get; set; } = new Vector3[]
{
new Vector3(1, 2, 3),
new Vector3(3, 2, 1),
}
从工具脚本设置导出变量¶
When changing an exported variable's value from a script in 工具模式, the value in the inspector won't be updated automatically. To update it, call NotifyPropertyListChanged() after setting the exported variable's value.
高级导出¶
为了避免不必要的复杂设计,不是所有导出类型都在语言层面上提供。下面将说明一些能用底层 API 实现的,较为常见的导出方法。
Before reading further, you should get familiar with the way properties are handled and how they can be customized with _Set(), _Get(), and _GetPropertyList() methods as described in 从对象访问数据或逻辑.
参见
要在 C++ 中用上述方法绑定属性,请参阅 使用 _set/_get/_get_property_list 绑定属性。
警告
脚本必须在 tool
模式运行,上述方法才能在编辑器内运行。