diff --git a/GFramework.Godot/extensions/NodeExtensions.cs b/GFramework.Godot/extensions/NodeExtensions.cs index c316b5d..13737d9 100644 --- a/GFramework.Godot/extensions/NodeExtensions.cs +++ b/GFramework.Godot/extensions/NodeExtensions.cs @@ -237,7 +237,25 @@ public static class NodeExtensions public static void SafeCallDeferred(this Node? node, string method) { // 检查节点是否为空且实例是否有效,有效时才执行延迟调用 - if (node != null && GodotObject.IsInstanceValid(node)) - node.CallDeferred(method); + if (node.IsValidNode()) + node!.CallDeferred(method); } + + + /// + /// 将指定节点转换为目标类型T + /// + /// 目标节点类型,必须继承自Node + /// 要转换的节点对象,可以为null + /// 转换后的目标类型节点 + /// 当节点无效或类型不匹配时抛出 + public static T OfType(this Node? node) where T : Node + { + // 检查节点是否有效且类型匹配 + if (node.IsValidNode()&& node is T t) + return t; + throw new InvalidCastException($"Cannot cast {node} to {typeof(T)}"); + } + + } \ No newline at end of file