My entity system for my game uses templates to lay out how entities are created. Something like:
EntityTemplateManager.register("zombie",
new PhysicsComponent(10), // speed
new SpriteComponent("zombie"), // graphic
new HealthComponent(100) // health
);
I like this part of the system because it makes sure I don’t miss any parameters or screw up their type.
Then I can create a new entity like this:
entity : Entity = EntityTemplateManager.create("zombie");
Pretty straight forward.
What I do now, to actually create the entity, is have the EntityTemplateManager create 1 entity to use as a default, then I call clone() on the entity and it goes through and clone()s all of its components and returns the result.
Actual code:
public function clone() : Entity
{
var components : Vector.<Component> = new Vector.<Component>();
var length : int = _components.length;
for (var i : int = 0; i < length; ++i)
components.push(_components[i].clone()); // copy my local components to the new entity
return new Entity(_name, _type, components);
}
The problem is, every time I create (design) a new component, I have to write (design) a clone() method inside of it AND keep track of all the parameters that were called on the constructor to create a brand new, default stated component.
So I end up with junk like this:
public class ComponentX
{
protected var _defaultName : String;
protected var _defaultStartingAnimation : String;
protected var _defaultBroadcastAnimationEnded : Boolean;
protected var _defaultOffsetX : Number;
protected var _defaultOffsetY : Number;
// other stuff hidden
public function ComponentX(name : String, startingAnimation : String, broadcastAnimationEnded : Boolean = false, offsetX : Number = 0, offsetY : Number = 0) : void
{
super();
_defaultName = name;
_defaultStartingAnimation = startingAnimation;
_defaultBroadcastAnimationEnded = broadcastAnimationEnded;
_defaultOffsetX = offsetX;
_defaultOffsetY = offsetY;
}
public function clone() : Component
{
return new ComponentX(_defaultName, _defaultStartingAnimation, _defaultBroadcastAnimationEnded, _defaultOffsetX, _defaultOffsetY);
}
// other methods
}
I really don’t like this — it’s wasteful and error prone.
How could I best store the parameters of the EntityTemplateManager.register() function (including the components’ constructors parameters) and use that new storage to create entities from instead?
I’ve tried some generic clone() methods like with a ByteArray or describeType(), but they don’t work with protected / private variables.
Ideas?
Few months ago I wrote my own Entity-Component manager too. I’ve done something like this (in your case):
Registering a new template works as below:
The
createfunction retrieves the specified component template and create components like this: