rokojori_action_library/Runtime/Godot/Extensions/NodeExtensions.cs

83 lines
1.6 KiB
C#

using Godot;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
using System.Reflection;
namespace Rokojori
{
public static class NodeExtensions
{
public static void CallDeferred( this Node node, System.Action action )
{
Callable.From( action ).CallDeferred();
}
public static int GetChildCountOfType<N>( this Node node )
{
var count = 0;
for ( int i = 0; i < node.GetChildCount(); i++ )
{
if ( node.GetChild( i ) is N )
{
count ++;
}
}
return count;
}
public static void EnsureChildCount<N>( this Node node, int neededChildCount, Action<N> callback = null ) where N:Node,new()
{
var segments = neededChildCount;
var ownCount = node.GetChildCount();
if ( ownCount == segments )
{
return;
}
if ( ownCount > segments )
{
node.DestroyChildrenRange( segments, ownCount - segments );
ownCount = segments;
}
for ( int i = ownCount; i < segments; i++ )
{
var n = node.CreateChild<N>();
if ( callback != null )
{
callback( n );
}
}
}
public static T GetNextSiblingOrChild<T>( this Node node ) where T:Node
{
var index = node.GetIndex();
var p = node.GetParent();
for ( int i = index + 1; i < p.GetChildCount(); i++ )
{
var child = p.GetChild( i );
if ( child != null && child is T t )
{
return t;
}
}
return Nodes.GetAnyChild<T>( node );
}
}
}