61 lines
1.9 KiB
C#
61 lines
1.9 KiB
C#
using Godot;
|
|
using System;
|
|
|
|
public static class VariantExtensions
|
|
{
|
|
/// <summary>
|
|
/// Converts a Godot Variant to a specified C# object type using a switch statement.
|
|
/// </summary>
|
|
/// <param name="variant">The variant to convert.</param>
|
|
/// <param name="targetType">The C# System.Type to convert to.</param>
|
|
/// <returns>An object of the target type, or throws an exception if conversion is not supported.</returns>
|
|
public static object AsType( this Variant variant, Type targetType )
|
|
{
|
|
// The switch statement uses type pattern matching (`when t == ...`)
|
|
// to check against the desired target type.
|
|
switch( targetType )
|
|
{
|
|
// Basic C# types
|
|
case Type t when t == typeof( bool ):
|
|
return variant.As<bool>();
|
|
|
|
case Type t when t == typeof( int ):
|
|
return variant.As<int>();
|
|
|
|
case Type t when t == typeof( long ):
|
|
return variant.As<long>();
|
|
|
|
case Type t when t == typeof( float ):
|
|
return variant.As<float>();
|
|
|
|
case Type t when t == typeof( double ):
|
|
return variant.As<double>();
|
|
|
|
case Type t when t == typeof( string ):
|
|
return variant.As<string>();
|
|
|
|
// Godot-specific structs
|
|
case Type t when t == typeof( Vector2 ):
|
|
return variant.As<Vector2>();
|
|
|
|
case Type t when t == typeof( Vector3 ):
|
|
return variant.As<Vector3>();
|
|
|
|
case Type t when t == typeof( Color ):
|
|
return variant.As<Color>();
|
|
|
|
// Handle enums (which are stored as integers in Variants)
|
|
case Type t when t.IsEnum:
|
|
return Enum.ToObject( t, variant.As<long>() );
|
|
|
|
// Handle Godot Objects (Nodes, Resources, etc.)
|
|
case Type t when t.IsSubclassOf( typeof( GodotObject ) ):
|
|
return variant.AsGodotObject(); // Use the built-in As(Type) for engine types
|
|
|
|
// Default case for unsupported types
|
|
default:
|
|
throw new ArgumentException( $"Conversion from Variant to type '{targetType.Name}' is not supported by this method." );
|
|
}
|
|
}
|
|
}
|