Hi all,
I hope everyone’s doing ok in their respective lockdowns!
I’m trying to implement Entities and Components but I’m struggling to understand how generics work in Haxe. This is what I’ve got:
Component
class Component {}
class ExampleComponent extends Component {
var thing: Int;
public function new() {
thing = 42;
}
}
Entity
class Entity {
var components: Map<String, Component>;
public function new() {
components = new Map();
}
@:generic
public function addComponents<C: Component>(components: Array<C>) {
for (component in components) {
var type = Type.getClass(component);
var name = Type.getClassName(type);
this.components.set(name, component);
}
}
@:generic
public function getComponent<C: Component>(type: Class<C>): Component {
var name = Type.getClassName(type);
var component = this.components.get(name);
return component;
}
}
(Any feedback on the general state of the above is much appreciated!)
What I’d like to be able to do is cast the component in getComponent
so I can return the type requested. Is that possible? In C# I could do it like this:
public C GetComponent<C>() where C : IComponent
{
Components.TryGetValue(typeof(C), out IComponent component);
return (C)component;
}
where Components is Dictionary<Type, IComponent> Components { get; set; }
.
Thanks!