iFactory.Godot/BITKit/Scripts/Builder/NodeBuilder.cs

73 lines
1.3 KiB
C#
Raw Normal View History

using Godot;
using System;
2023-07-18 20:57:02 +08:00
using System.Collections.Generic;
// ReSharper disable MemberCanBePrivate.Global
namespace BITKit;
public partial class NodeBuilder : Node
{
[Export] private bool clearOnStart = true;
[Export] private bool clearTemplateOnly = true;
2023-07-17 04:10:14 +08:00
[ExportCategory("UX")]
[Export] private Control emptyHints;
[ExportCategory("Template")]
[Export] private PackedScene template;
2023-07-18 20:57:02 +08:00
public Node[] Instances => _instances.ToArray();
private readonly List<Node> _instances = new List<Node>();
public override void _Ready()
{
if (clearOnStart)
{
Clear();
}
}
2023-09-17 02:55:33 +08:00
public T Build<T>() where T : Node, new()
{
2023-07-17 04:10:14 +08:00
Node instance;
if (template is not null)
{
2023-07-17 04:10:14 +08:00
instance = template.Instantiate<T>();
AddChild(instance);
}
else
{
2023-09-17 02:55:33 +08:00
instance = this.Create<T>();
}
2023-07-17 04:10:14 +08:00
2023-09-17 02:55:33 +08:00
emptyHints?.Hide();
2023-07-18 20:57:02 +08:00
_instances.Add(instance);
2023-09-17 02:55:33 +08:00
return (T)instance;
}
2023-07-17 04:10:14 +08:00
public void Clear()
{
2023-07-18 20:57:02 +08:00
_instances.Clear();
emptyHints?.Show();
2023-09-17 02:55:33 +08:00
if (clearTemplateOnly && template is not null)
{
2023-07-17 04:10:14 +08:00
foreach (var x in GetChildren())
{
2023-07-17 04:10:14 +08:00
switch (template)
{
case null:
x.QueueFree();
break;
case (var y) when y.ResourcePath == x.SceneFilePath:
x.QueueFree();
break;
}
}
}
else
{
2023-07-17 04:10:14 +08:00
MathNode.ClearChild(this);
}
}
}