From a2c7bf7d06405428f54fa79885adc1df98321c6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20L=C3=BCbe=C3=9F?= Date: Sun, 17 Mar 2024 20:25:38 +0100 Subject: [PATCH] Ensure generating unique Entity IDs --- GlitchyEngine/src/World/Components/Components.bf | 3 +-- GlitchyEngine/src/World/Scene.bf | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/GlitchyEngine/src/World/Components/Components.bf b/GlitchyEngine/src/World/Components/Components.bf index 2faa3c3..41d0c70 100644 --- a/GlitchyEngine/src/World/Components/Components.bf +++ b/GlitchyEngine/src/World/Components/Components.bf @@ -24,10 +24,9 @@ namespace GlitchyEngine.World { public readonly UUID ID; - /// Create a new IDComponent with a random UUID. public this() { - ID = UUID.Create(); + ID = .Zero; } public this(UUID id) diff --git a/GlitchyEngine/src/World/Scene.bf b/GlitchyEngine/src/World/Scene.bf index 20971f0..167de44 100644 --- a/GlitchyEngine/src/World/Scene.bf +++ b/GlitchyEngine/src/World/Scene.bf @@ -834,7 +834,7 @@ namespace GlitchyEngine.World } /// Creates a new Entity with the given name. - public Entity CreateEntity(StringView name = "", UUID id = default) + public Entity CreateEntity(StringView name = "", UUID id = .Zero) { Entity entity = Entity(_ecsWorld.NewEntity(), this); entity.AddComponent(); @@ -848,7 +848,7 @@ namespace GlitchyEngine.World #endif // If no id is given generate a random one. - IDComponent idComponent = (id == default) ? IDComponent() : IDComponent(id); + IDComponent idComponent = (id == .Zero) ? IDComponent(CreateEntityId()) : IDComponent(id); entity.AddComponent(idComponent); @@ -857,6 +857,18 @@ namespace GlitchyEngine.World return entity; } + /// Creates a new entity Id that is unique within this scene. + public UUID CreateEntityId() + { + while (true) + { + UUID entityId = UUID.Create(); + + if (!_idToEntity.ContainsKey(entityId)) + return entityId; + } + } + /** Deletes the given entity. * @param entity The entity to delete. * @param destroyChildren If set to true all children of entity will be destroyed.