cirnogodot/Scripts/Utils/Tools3D.cs
2025-06-19 17:55:23 +02:00

64 lines
No EOL
2.2 KiB
C#

using Godot;
namespace Cirno.Scripts.Utils;
public static class Tools3D
{
public static T CreateChild<T>(this Node3D node, PackedScene prefab) where T : Node3D
{
return CreateChild<T>(node, prefab, node.GlobalPosition);
}
public static T CreateChild<T>(this Node3D node, PackedScene prefab, Vector3 position) where T : Node3D
{
return CreateChildOf<T>(node, node, prefab, position);
// if (prefab == null) return null;
// var newInstance = prefab.Instantiate<T>();
// node.GetParent().CallDeferred("add_child", newInstance);
// // Need to use parent instead of owner because tilemap scenes have no owner
// //node.Owner.CallDeferred("add_child", newInstance);
// newInstance.Transform = node.GlobalTransform;
// newInstance.Position = position;
//
// return newInstance;
}
public static T CreateSibling<T>(this Node3D node, PackedScene prefab) where T : Node3D
{
return CreateChildOf<T>(node, node.GetParent<Node3D>(), prefab, node.GlobalPosition);
}
public static T CreateSibling<T>(this Node3D node, PackedScene prefab, Vector3 position) where T : Node3D
{
return CreateChildOf<T>(node, node.GetParent<Node3D>(), prefab, position);
}
public static T CreateChildOf<T>(this Node3D node, Node3D parentNode, PackedScene prefab) where T : Node3D
{
return CreateChildOf<T>(node, parentNode, prefab, node.GlobalPosition);
}
public static T CreateChildOf<T>(this Node3D node, Node3D parentNode, PackedScene prefab, Vector3 position) where T : Node3D
{
if (prefab == null)
{
GD.PrintErr("Tried to instantiate a null prefab");
return null;
}
if (parentNode == null)
{
GD.PrintErr("Tried to instantiate child of a null parent");
return null;
}
var newInstance = prefab.Instantiate<T>();
//node.GetParent().CallDeferred("add_child", newInstance);
parentNode.CallDeferred("add_child", newInstance);
//newInstance.Transform = node.GlobalTransform;
newInstance.Position = parentNode.ToLocal(position);
return newInstance;
}
}