WIP reworking the item repository

This commit is contained in:
2025-09-09 23:57:55 +02:00
parent 9f50e1d293
commit d1a8ff0cbf
9 changed files with 97 additions and 75 deletions
@@ -16,6 +16,7 @@ public partial class FieldBehaviour2D : Sprite2D
[Export] public FieldState FieldState = FieldState.Tilled;
[Export] public InteractionArea2D PlantingInteraction;
[Export] public Node2D PlantingPlaceholder;
[Export] public ItemRepository ItemRepository;
public Vector2 FieldPosition;
@@ -83,24 +84,25 @@ public partial class FieldBehaviour2D : Sprite2D
if (item == null || PlantingPlaceholder.GetChildCount() > 0)
return success;
PackedScene? plantPrefab = item.blueprint.itemPrefab;
string prefabPath = ItemRepository.TryGetPrefabPath(item.blueprint);
if (plantPrefab != null)
if (prefabPath != null)
{
Node plantInstance = plantPrefab.Instantiate();
if (plantInstance is Node2D plant2d)
{
PlantingPlaceholder.AddChild(plant2d);
plant2d.GlobalPosition = PlantingPlaceholder.GlobalPosition;
PlantBehaviour2D? plantBehaviour = plant2d as PlantBehaviour2D;
if (plantBehaviour != null)
{
plantBehaviour.Field = this;
}
success = true;
// todo: Error: cannot convert value at key from string to object
PackedScene prefab = ResourceLoader.Load<PackedScene>(prefabPath, nameof(PackedScene));
Node2D plant2d = prefab.Instantiate<Node2D>();
PlantingPlaceholder.AddChild(plant2d);
plant2d.GlobalPosition = PlantingPlaceholder.GlobalPosition;
PlantBehaviour2D? plantBehaviour = plant2d as PlantBehaviour2D;
if (plantBehaviour != null)
{
plantBehaviour.Field = this;
}
success = true;
}
return success;
@@ -0,0 +1,28 @@
using Godot;
using Godot.Collections;
namespace Babushka.scripts.CSharp.Common.Inventory;
/// <summary>
/// A dictionary wrapper resource that holds references to ItemResources and maps them to their respective prefabs.
/// </summary>
[GlobalClass]
public partial class ItemRepository : Resource
{
[Export] public Dictionary<ItemResource, string> itemInventoryRepository;
/// <summary>
/// Returns the path to the itemPrefab for the inventory item.
/// </summary>
/// <param name="resource"></param>
/// <returns></returns>
public string TryGetPrefabPath(ItemResource resource)
{
if (itemInventoryRepository.Keys.Contains(resource))
{
return itemInventoryRepository[resource];
}
return null;
}
}
@@ -17,15 +17,11 @@ public partial class ItemResource : Resource
[Export]
public int maxStack;
[Export]
public PackedScene? itemPrefab;
public ItemResource()
{
name = "";
color = Colors.Red;
maxStack = 1;
itemPrefab = null;
}
}