C# Variant¶
For a detailed explanation of Variant in general, see the Variant documentation page.
Godot.Variant
is used to represent Godot's native Variant type. Any Variant-compatible type can be converted from/to it.
We recommend avoiding Godot.Variant
unless it is necessary to interact with untyped engine APIs.
Take advantage of C#'s type safety when possible.
Any of Variant.As{TYPE}
methods or the generic Variant.As<T>
method can be used to convert
a Godot.Variant
to a C# type. Since the Godot.Variant
type contains implicit conversions
defined for all the supported types, calling these methods directly is usually not necessary.
Use CreateFrom
method overloads or the generic Variant.From<T>
method to convert a C# type
to a Godot.Variant
.
Note
Since the Variant type in C# is a struct, it can't be null. To create a "null"
Variant use the default
keyword or the parameterless constructor.
Variant-compatible types¶
All the built-in value types, except
decimal
,nint
andnuint
.string
.Classes derived from GodotObject.
Collections types defined in the
Godot.Collections
namespace.
Full list of Variant types and their equivalent C# type:
Variant.Type |
C# Type |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Warning
Godot uses 64-bit integers and floats in Variant. Smaller integer and float types
such as int
, short
and float
are supported since they can fit in the
bigger type. Be aware that an implicit conversion is performed so using the wrong
type will result in potential precision loss.
Warning
Enums are supported by Godot.Variant
since their underlying type is an integer
type which are all compatible. However, implicit conversions don't exist, enums must
be manually converted to their underlying integer type before they can converted to/from
Godot.Variant
or use the generic Variant.As<T>
and Variant.From<T>
methods
to convert them.
enum MyEnum { A, B, C }
Variant variant1 = (int)MyEnum.A;
MyEnum enum1 = (MyEnum)(int)variant1;
Variant variant2 = Variant.From(MyEnum.A);
MyEnum enum2 = variant2.As<MyEnum>();