cirnogodot/Scripts/Tools.cs
2025-02-07 14:58:59 +01:00

79 lines
2.4 KiB
C#

using Godot;
namespace Cirno.Scripts;
public static class Tools
{
public static T CreateChild<T>(this Node2D node, PackedScene prefab) where T : Node2D
{
return CreateChild<T>(node, prefab, node.GlobalPosition);
}
public static T CreateChild<T>(this Node2D node, PackedScene prefab, Vector2 position) where T : Node2D
{
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 Node2D node, PackedScene prefab) where T : Node2D
{
return CreateChildOf<T>(node, node.GetParent<Node2D>(), prefab, node.GlobalPosition);
}
public static T CreateSibling<T>(this Node2D node, PackedScene prefab, Vector2 position) where T : Node2D
{
return CreateChildOf<T>(node, node.GetParent<Node2D>(), prefab, position);
}
public static T CreateChildOf<T>(this Node2D node, Node2D parentNode, PackedScene prefab) where T : Node2D
{
return CreateChildOf<T>(node, parentNode, prefab, node.GlobalPosition);
}
public static T CreateChildOf<T>(this Node2D node, Node2D parentNode, PackedScene prefab, Vector2 position) where T : Node2D
{
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;
}
public static GameManager GetGameManager(this Node2D node)
{
return node.GetNode<GameManager>("/root/GameScene");
}
public static AlarmManager GetAlarmManager(this Node2D node)
{
return node.GetNodeOrNull<AlarmManager>("/root/GameScene/AlarmManager");
}
public static InventoryManager GetInventoryManager(this Node2D node)
{
return node.GetNodeOrNull<InventoryManager>("/root/GameScene/InventoryManager");
}
}