using Godot;
using System;
public static class VariantExtensions
{
///
/// Converts a Godot Variant to a specified C# object type using a switch statement.
///
/// The variant to convert.
/// The C# System.Type to convert to.
/// An object of the target type, or throws an exception if conversion is not supported.
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();
case Type t when t == typeof( int ):
return variant.As();
case Type t when t == typeof( long ):
return variant.As();
case Type t when t == typeof( float ):
return variant.As();
case Type t when t == typeof( double ):
return variant.As();
case Type t when t == typeof( string ):
return variant.As();
// Godot-specific structs
case Type t when t == typeof( Vector2 ):
return variant.As();
case Type t when t == typeof( Vector3 ):
return variant.As();
case Type t when t == typeof( Color ):
return variant.As();
// Handle enums (which are stored as integers in Variants)
case Type t when t.IsEnum:
return Enum.ToObject( t, variant.As() );
// 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." );
}
}
}