Hello Folks!
I want to replicate the getComponent() method from Unity in Java. For those who have not yet developed with the Unity engine, here is a short explanation:
How does the method work?
In Unity, you can attach Components to GameObjects. There are then different subtypes for different functionalities, e.g. the Component “MeshFilter” to render meshes.
How to use the method?
It is very easy. GetComponent() searches for the attached MeshFilter-Component and returns it as MeshFilter object. The type is really the only parameter here.
Well, in Java, I have created an ArrayList for the beginning. There I want to collect the attached Components for a game class. I want to use it for my model classes, since I separate Model and Visualisation in my Game.
At the moment I am writing the getComponent method. It should work like explained above: It is generic and takes one generic type parameter T, and no more parameters. Now I want to search for the one Component Object inside the ArrayList, which subtype is of the type of T.
Well, I do not do so well right now. My approach was to iterate through all the contents and compare the types:
public class DataModel
{
private ArrayList<Component> components;
public <T> T getComponent()
{
T result;
for (Component component : components) {
// Subtype of component == T?
}
return result;
}
}
However, I do not know how to check for a subtype of a class neither in a Generics case, nor in a specific Class case (1) and there also seems to be a problem with the Generic Type Variable T, as it did not recognise it as a Type in experiments (2).
Do you have an idea how to accomplish that case? Or, is it even possible to do that in Java?