65 lines
1.8 KiB
C#
65 lines
1.8 KiB
C#
|
|
using Godot.Collections;
|
||
|
|
|
||
|
|
namespace Godot.Sharp.Extended.Tools;
|
||
|
|
|
||
|
|
public static class NodeExtensions
|
||
|
|
{
|
||
|
|
public static void AddToGroup(this Node node) => node.AddToGroup(node.GetType().Name);
|
||
|
|
public static T GetNode<T>(this Node node) where T : Node => node.GetNode<T>(typeof(T).Name);
|
||
|
|
public static Array<T> GetChildrenOfType<T>(this Node node) where T : Node
|
||
|
|
{
|
||
|
|
var children = node.GetChildren();
|
||
|
|
|
||
|
|
return new Array<T>(children.OfType<T>().ToArray());
|
||
|
|
}
|
||
|
|
public static T? GetFirstChildOfType<T>(this Node node) where T : Node => GetChildrenOfType<T>(node).FirstOrDefault();
|
||
|
|
|
||
|
|
public static void RemoveAllChildren(this Node node)
|
||
|
|
{
|
||
|
|
foreach (var child in node.GetChildren())
|
||
|
|
node.RemoveChild(child);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static void RemoveAndQueueFreeChildren(this Node node)
|
||
|
|
{
|
||
|
|
foreach (var child in node.GetChildren())
|
||
|
|
{
|
||
|
|
node.RemoveChild(child);
|
||
|
|
child.QueueFree();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public static void QueueFreeChildren(this Node node)
|
||
|
|
{
|
||
|
|
foreach (var child in node.GetChildren())
|
||
|
|
node.QueueFree();
|
||
|
|
}
|
||
|
|
|
||
|
|
public static T? GetAncestor<T>(this Node node) where T : Node
|
||
|
|
{
|
||
|
|
Node current = node;
|
||
|
|
Node root = node.GetTree().Root;
|
||
|
|
while (current != root && !(current is T))
|
||
|
|
current = current.GetParent();
|
||
|
|
|
||
|
|
return current as T;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static Node? GetLastChild(this Node node)
|
||
|
|
{
|
||
|
|
var count = node.GetChildCount();
|
||
|
|
if (count == 0) return null;
|
||
|
|
return node.GetChild(count - 1);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static T? GetLastChild<T>(this Node node) where T : Node
|
||
|
|
{
|
||
|
|
Node? last = null;
|
||
|
|
foreach (var child in node.GetChildren())
|
||
|
|
{
|
||
|
|
if (child is T) last = child;
|
||
|
|
}
|
||
|
|
|
||
|
|
return last as T;
|
||
|
|
}
|
||
|
|
}
|