65 lines
1.5 KiB
C#
65 lines
1.5 KiB
C#
using Godot;
|
|
using System.Collections.Generic;
|
|
|
|
namespace AceFieldNewHorizon.Scripts.System;
|
|
|
|
public partial class Hud : CanvasLayer
|
|
{
|
|
private ResourceManager _resourceManager;
|
|
private VBoxContainer _resourceDisplay;
|
|
private readonly Dictionary<string, Label> _resourceLabels = new();
|
|
|
|
public override void _Ready()
|
|
{
|
|
_resourceDisplay = GetNode<VBoxContainer>("ResourceDisplay");
|
|
|
|
_resourceManager = DependencyInjection.Container.GetInstance<ResourceManager>();
|
|
if (_resourceManager == null)
|
|
{
|
|
GD.PushError("ResourceSystem not found in the scene tree!");
|
|
return;
|
|
}
|
|
|
|
_resourceManager.OnResourceChanged += UpdateResourceDisplay;
|
|
|
|
// Initialize display with current resources
|
|
foreach (var entry in _resourceManager.GetAllResources())
|
|
{
|
|
UpdateResourceDisplay(entry.Key, entry.Value);
|
|
}
|
|
}
|
|
|
|
private void UpdateResourceDisplay(string resourceId, int newAmount)
|
|
{
|
|
if (!_resourceLabels.TryGetValue(resourceId, out Label label))
|
|
{
|
|
label = new Label();
|
|
_resourceDisplay.AddChild(label);
|
|
_resourceLabels.Add(resourceId, label);
|
|
}
|
|
|
|
if (newAmount <= 0)
|
|
{
|
|
// Remove label if resource amount is zero or less
|
|
if (label.GetParent() != null)
|
|
{
|
|
_resourceDisplay.RemoveChild(label);
|
|
}
|
|
_resourceLabels.Remove(resourceId);
|
|
label.QueueFree(); // Free the label from memory
|
|
}
|
|
else
|
|
{
|
|
label.Text = $"{resourceId}: {newAmount}";
|
|
}
|
|
}
|
|
|
|
public override void _ExitTree()
|
|
{
|
|
if (_resourceManager != null)
|
|
{
|
|
_resourceManager.OnResourceChanged -= UpdateResourceDisplay;
|
|
}
|
|
}
|
|
}
|