diff --git a/README.md b/README.md index 5feba24..2b2a069 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,9 @@ class InitConfigSystem < ECS::System def init config = ...some config initializatio @world.new_entity.add(Config.new(config)) + + # another way + @world.add(Config.new(config)) unless @world.component_exists?(Config) end end diff --git a/spec/myecs_spec.cr b/spec/myecs_spec.cr index 5a5a063..ace8c98 100644 --- a/spec/myecs_spec.cr +++ b/spec/myecs_spec.cr @@ -463,6 +463,17 @@ describe ECS::Singleton do world.getConfig.value.should eq 100 world.getConfig_ptr.value.value.should eq 100 end + + it "can be added and deleted from a world" do + world = ECS::World.new + expect_raises(Exception) { world.getConfig } + world.getConfig?.should be_nil + world.add(Config.new(100)) + world.getConfig?.should be_truthy + world.getConfig.value.should eq 100 + world.remove(Config) + world.getConfig?.should be_nil + end end class SystemGenerateEvent(Event) < ECS::System diff --git a/src/myecs.cr b/src/myecs.cr index 33dd50d..269db19 100644 --- a/src/myecs.cr +++ b/src/myecs.cr @@ -635,16 +635,33 @@ module ECS {% if obj.annotation(ECS::Singleton) %} {% obj_name = obj.id.split("::").last.id %} def get{{obj_name}} - @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(Entity.new(self, NO_ENTITY)) || raise "{{obj}} was not created" + @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(NO_ENTITY) || raise "{{obj}} was not created" end def get{{obj_name}}? - @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(Entity.new(self, NO_ENTITY)) + @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(NO_ENTITY) end def get{{obj_name}}_ptr - @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component_ptr(Entity.new(self, NO_ENTITY)) + @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component_ptr(NO_ENTITY) end + + def add(comp : {{obj}}) + @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).add_component(NO_ENTITY, comp) + end + + def set(comp : {{obj}}) + @pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).add_or_update_component(NO_ENTITY, comp) + end + + def remove(typ : {{obj}}.class) + @pools[{{COMP_INDICES[obj]}}].remove_component(NO_ENTITY) + end + + def remove_if_present(typ : {{obj}}.class) + @pools[{{COMP_INDICES[obj]}}].try_remove_component(NO_ENTITY) + end + {% end %} {% end %}