Made trash object delete its entity when collected

This commit is contained in:
jonathan
2026-02-04 15:32:11 +01:00
parent 628da80ed3
commit 971d8d461b
9 changed files with 46 additions and 23 deletions
@@ -28,5 +28,8 @@ public abstract class PositionalEntity : Entity
// Deals with Instantiation of the node
public abstract void InstantiateEntityNode(Node2D parent);
// Deals with Removal of the node before the whole scene is unloaded
public abstract void RemoveEntityNode();
}
@@ -1,3 +1,4 @@
using Babushka.scripts.CSharp.GameEntity.EntityNodes;
using Babushka.scripts.CSharp.GameEntity.Management;
using Godot;
@@ -8,16 +9,26 @@ public class TrashEntity : PositionalEntity
public override string EntityType => OWN_TYPE_NAME;
public const string OWN_TYPE_NAME = "TrashEntity";
private EntityNodeCreator _creator;
private TrashEntityNode? _entityNode;
public TrashEntity()
{
}
public override void InstantiateEntityNode(Node2D parent)
{
if(_creator == null) _creator = EntityManager.Instance.NodeCreator;
if (_creator == null) _creator = EntityManager.Instance.NodeCreator;
var entityNode = _creator.InstantiateNode(EntityType);
parent.AddChild(entityNode);
entityNode.GlobalPosition = position;
var trashEntityNode = (TrashEntityNode)entityNode;
trashEntityNode.Initialize(this);
_entityNode = trashEntityNode;
}
public override void RemoveEntityNode()
{
if(_entityNode.IsValid())
_entityNode!.QueueFree();
}
}
@@ -1,4 +1,5 @@
using Babushka.scripts.CSharp.GameEntity.Entities;
using Babushka.scripts.CSharp.GameEntity.Management;
using Godot;
namespace Babushka.scripts.CSharp.GameEntity.EntityNodes;
@@ -9,8 +10,11 @@ public partial class TrashEntityNode : Node2D
public void Initialize(TrashEntity trashEntity)
{
_trashEntity = trashEntity;
_trashEntity = trashEntity;
}
public void Collect()
{
EntityManager.Instance.RemoveEntity(_trashEntity);
}
}
@@ -154,4 +154,12 @@ public partial class EntityManager : Node
#endregion
public void RemoveEntity(Entity entity)
{
_allEntities.Remove(entity);
if (entity is PositionalEntity positionalEntity)
{
positionalEntity.RemoveEntityNode();
}
}
}
@@ -1,4 +1,5 @@
using PositionalEntity = Babushka.scripts.CSharp.GameEntity.Entities.PositionalEntity;
using Godot;
using PositionalEntity = Babushka.scripts.CSharp.GameEntity.Entities.PositionalEntity;
namespace Babushka.scripts.CSharp.GameEntity.Management;
@@ -11,4 +12,11 @@ public static class EntityManagerUtil
self.AddEntity(entity);
}
public static bool IsValid<T>(this T? node) where T : GodotObject
{
return node != null
&& GodotObject.IsInstanceValid(node)
&& !node.IsQueuedForDeletion();
}
}