I am writing an Entity Component System for a game engine in Java (using LibGDX).
I have an entity with an arraylist of various components. Each component inherits from a base Component class.
I want to have a method on my entity that can give me a reference to a component of a specific type (e.g., a RenderComponent, a PhysicsComponent, etc.). I have tried the following, but it doesn't seem to work.
public class Entity
{
private ArrayList<Component> _components;
...
public void AddComponent(Component c)
{
_components.add(c);
c.Enable();
}
public Component GetComponent(String componentType)
{
Component s = null;
for (int i = 0; i < _components.size(); i++)
{
if (_components.get(i).getClass().getSimpleName() == componentType)
s = _components.get(i);
}
return s;
}
}
The returned object is null.
How should I do this? Is there a more clever way to make the parameters specify a type (instead of a simple string)?
Also, what if I want ALL components of a specific type? How should I deal with that?
I read a bit about reflection, but I have never used it. I am still quite new to Java programming.
Thanks in advance.
instanceOf==withString, that's probably the issue here