✨ Hud basis
This commit is contained in:
64
Scripts/System/Hud.cs
Normal file
64
Scripts/System/Hud.cs
Normal file
@@ -0,0 +1,64 @@
|
||||
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 = GetTree().CurrentScene.GetNode<ResourceManager>("ResourceSystem");
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user